© Mikael Olsson 2019
Mikael OlssonModern C Quick Syntax Referencehttps://doi.org/10.1007/978-1-4842-4288-9_17

17. Constants

Mikael Olsson1 
(1)
Hammarland, Länsi-Suomi, Finland
 

A constant is a variable with a value that cannot be changed once it has been assigned. This allows the compiler to enforce that a variable’s value is not changed anywhere in the code by mistake.

Constant Variables

A variable can be made into a constant by adding the const keyword either before or after the data type. This modifier makes the variable read-only, and it must therefore be assigned a value at the same time as it is declared. Attempting to change the constant anywhere else results in a compile-time error.
const int var = 5;   /* recommended order */
int const var2 = 10; /* alternative order */

Constant Pointers

When it comes to pointers, const can be used in two ways. First, the pointer can be made constant, which means that it cannot be changed to point to another location.
int myPointee;
int* const p = &myPointee; /* constant pointer */
Second, the pointee can be declared constant. This means that the variable pointed to cannot be modified through this pointer.
const int* q = &var; /* constant pointee */
It is possible to declare both the pointer and the pointee as constant to make them both read-only.
const int* const r = &var; /* constant pointer & pointee */
Referencing a constant from a non-constant pointer will produce a warning or error on most compilers. This is because such an assignment makes it possible to accidentally rewrite the constant’s value.
int* s = &var; /* error: const to non-const assignment */

Constant Parameters

Function parameters can be made constant to prevent them from being altered within the function. The main benefit of this is to let programmers know that the function leaves its pointer arguments untouched. When used consistently, it can also provide information about which functions can be expected to modify their pointer arguments.
#include <stdio.h>
void foo(const int* x) {
  if (x != NULL) {
    int i = *x; /* allowed */
    *x = 1;     /* compile-time error */
  }
}

Constant Guideline

In general, it is a good idea to always declare variables as constants if they do not need to be modified. This ensures that the variables are not changed anywhere in the program by mistake, which in turn can help prevent bugs.