Const

From Chilipedia
Revision as of 22:18, 11 September 2017 by Chili (Talk | contribs) (Pointers)

Jump to: navigation, search

const is a keyword that is applied to variables, references, and functions. It's basically like entering into a contract with the compiler that says "Shit's not gonna change yo!". A lot of scrub-level devs overlook this feature, but it is the shit and will make your code almost as rock SOLID as Chili's Johnson.

Why const?

You often have variables where you store the result of some calculation, for example, but you don't ever have to modify the variable during its lifetime. Mark that shit as const! That way, the compiler will tell you if you fuck up and accidentally write some code that would modify the variable. Take this code:

void foo( const int defcon )
{
   if( defcon = 1 )     //< FLAGGED AS COMPILER ERROR! WORLD SAVED!
   {
       fire_missiles();
   }
}

Without the const, the operation would store the value 1 in the variable defcon, then the value of defcon would convert to the boolean value true, and the world would be fucked! This is just a simple example; proper use of const can solidify your code in many ways.

Use Cases

There are a number of different situations where you can use const, and the meaning of the keyword changes somewhat depending on the situation.

Variables

You can declare a variable as const with the following syntax.

const int x = 69;

When a variable is declared in this manner, operations that modify the variable will cause a compiler error. It will also be impossible to pass a pointer or reference of that variable, unless the pointer or reference is also const.

References

You can declare a const reference as follows:

const int& x_ref = x;

This is especially useful in function declarations, where we want to pass an object by reference (we don't wanna copy the whole damn thing!), but we aren't going to be modifying it:

void DoSomeShit( const MyObjectType& obj );

Declaring a reference parameter like this prevents code in the function body from modifying the object, and it also enables us to pass const objects to this function (if the reference were not const, we would not be allowed to pass in const objects).

Pointers

Much like references, you can declare const pointers that are not allowed to modify their targets.

const int* px = &x;
void DoSomeShit( const MyObjectType* obj );

We sometimes call these, 'pointer-to-const', because it is the object that they point to that is not modifiable. There is another kind of const pointer, defined like this:

int* const px = &x;

This kind of const pointer is not retargettable. So here it is the pointer itself that is being locked down. You can also have both!

const int* const px = &x;

This pointer cannot be retargetted, and it cannot modify its target.