![]() |
const | Keyword |
Keyword Index |
Makes variable value or pointer parameter unmodifiable.
When const
is used with a variable, it uses the following syntax:
const variable-name [ = value];In this case, the
const
modifier allows you to assign an initial
value to a variable that cannot later be changed by the program. For
example,
const my_age = 32;Any assignments to
'my_age'
will result in a compiler error. However,
such declaration is quite different than using
#define my_age 32In the first case, the compiler allocates a memory for
'my_age'
and stores
the initial value 32 there, but it will not allow any later assignment to this variable.
But, in the second case, all occurences of 'my_age'
are simply replaced with 32
by the preprocessor, and no memory will be allocated for it.
*(int*)&my_age = 35;When the
const
modifier is used with a pointer parameter in a function's parameter
list, it uses the following syntax:
function-name (const type *var-name)Then, the function cannot modify the variable that the pointer points to. For example,
int printf (const char *format, ...);Here the
printf
function is prevented from modifying the format string.