Difference between revisions of "Const"
(Created page with "<code>const</code> is a keyword that is applied to variable, references, and function. It's basically like entering into a contract with the compil...") |
|||
Line 1: | Line 1: | ||
− | <code>const</code> is a keyword that is applied to [[ | + | <code>const</code> is a keyword that is applied to [[variable|variables]], references, and [[function|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 <code>const</code>? == | == Why <code>const</code>? == |
Revision as of 22:14, 11 September 2017
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& x_ref = x;
void DoSomeShit( const MyObjectType& obj );