Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

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
This code will compile with no problems. When I compile and run it, I see the
following -

You might also like