main() { const float pi = 3.14; } |
The const keyword is used as a qualifier to the following data types - int float char double struct.
const int degrees = 360; const float pi = 3.14; const char quit = 'q'; |
void Func(const char *Str); main() { char *Word; Word = (char *) malloc(20); strcpy(Word, "Sulphate"); Func(Word); } void Func(const char *Str) { } |
The const char *Str
tells the compiler that the DATA the
pointer points too is const
. This means, Str can be changed
within Func, but *Str cannot. As a copy of the pointer is passed to Func,
any changes made to Str are not seen by main....
-------- | Str | Value can be changed -----|-- | | V -------- | *Str | Read Only - Cannot be changed. -------- |
I am not sure if this applies to all compilers, but, you can place the 'const' after the datatype, for example:
int const degrees = 360; float const pi = 3.14; char const quit = 'q'; |
are all valid in 'gcc'.
main() { const char * const Variable1; char const * const Variable2; }; |
These both make the pointer and the data read only. Here are a few more examples.
const int Var; /* Var is constant */ int const Var; /* Ditto */ int * const Var; /* The pointer is constant, * the data its self can change. */ const int * Var; /* Var can not be changed. */ |
C++ version of const
Top | Master Index | Keywords | Functions |