Skip to main content

C-language

C: const is not constant!

const does not mean that the variable is constant. In this post, we explore the true meaning of the const qualifier and its implications.

In C, const is a type qualifier that is used to specify that a variable's value cannot be modified after it has been initialized. The const type of variable is a read-only variable, meaning that it can be read but cannot be changed.

🛑
This understanding of the const keyword is misleading!

The reassignment of c to X in the following code is not allowed!

#include <stdio.h>

int main() {
    volatile const char c = 'A';

    c = 'X';

    printf(" &c: %p |    c: %c\n", &c, c);

    return 0;
}
Experiment #1
❯ gcc main.c
main.c:6:7: error: cannot assign to variable 'c' with const-qualified type 'const volatile char'
    c = 'X';
    ~ ^
main.c:4:25: note: variable 'c' declared const here
    volatile const char c = 'A';
    ~~~~~~~~~~~~~~~~~~~~^~~~~~~
1 error generated.

So, a const variable cannot be modified?

Now try this

What do you think the output of the following code will be?

#include <stdio.h>

int main() {
    volatile const char c = 'A';
    char *ptr = (char *)&c;

    printf(" &c: %p |    c: %c\n", &c, c);

    *ptr = 'X';

    printf(" &c: %p |    c: %c\n", &c, c);
    printf("ptr: %p | *ptr: %c\n", ptr, *ptr);

    return 0;
}
Experiment #2