The const keyword.


The const keyword is used to create a read only variable. Once initialised, the value of the variable cannot be changed but can be used just like any other variable. It has a type, and takes up space in memory.

const syntax


        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'; 

const and pointers.

Consider the following example.


        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.
            --------

Geeky Stuff

It is still possible to change the contents of a 'const' variable. Consider this program it creates a const variable and then changes its value by accessing the data by another name.

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'.

More Geeky Stuff

What would you expect these to do?


        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. */  
                           


See Also.

o #define preprocessor

o C++ version of const


An Example.

o const example.


Top Master Index Keywords Functions


Martin Leslie