Const Pointers and Pointers to Const Values in C

In C, the syntax and semantics of pointers that are const and pointers to const values can be a bit confusing.

Constants

Constants can be used like variables but it is only possible to read from them. Changing their initial value is not allowed.

This is where things are still simple. So let’s start with ordinary constants:

#include <stdio.h>

int main(void)
{
    const int number = 42;
    const char str[] = "Hello World";

    // It is not allowed to change the value of a const variable:
    //number = 5; // Compile Error!!!

    // Same here:
    //str[5] = 'N'; // Compile Error!!!

    printf("Number: %d\n", number);
    printf("Str: %s\n", str);
}
Continue reading “Const Pointers and Pointers to Const Values in C”