const keyword

Jyothi
2 min readNov 23, 2024

--

The const keyword is used to declare variables whose value cant be changed after initialisation, it is mainly used for creating the read-only variables. It helps in avoiding modifications to data.

Some examples of const keyword usage:

const int val = 199; // val variable value cant be changed after.

const with pointers:

  • Pointer to constant data

const int *ptr = &val; // cannot change the value of the pointer

Below stmt gives compilation error:

ptr = 59;

But ptr can point to another address:

int var1;

ptr = &var1;

  • Constant pointer to data:

int const *cptr = &val; // cannot change the pointer address

Below stmt gives compilation error, ie while assigning to different address:

cptr = &var1;

But value can be changed:

cptr = 88;

  • constant pointer to constant data:

const int const *ccptr = &val; // cannot change value and address.

  • const with volatile

const volatile int reg = 0x0880; // reg value will not change code, but might change by hw. volatile keyword is not to optimize the stmt

  • const keyword can be used to pass the parameter to functions which process data but will not modify the values. It ensures that function does not modify the input data and prevents accidental changes.
  • const keyword can be used with return data types which returns read-only values or pointers.
  • const keyword can be used with global variables.
  • const in structure fields. That parameter value can be initialised at the declaration time.
  • const with dynamic memory allocation. You can allocate memory for const data to ensure it cannot be modified.

Notes:

  • const variable must be initialised during declaration
  • const keyword compared to preprocessor enforces type checking, provides better debugging and has a memory address.
  • If you try to modify the const variable by type casting it then there will be undefined behaviour.

--

--

No responses yet