Professional Documents
Culture Documents
Volatile
Volatile
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';
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?
#include <stdio.h>
int main() {
volatile const char c = 'A';
char *ptr = (char *)&c;
*ptr = 'X';
return 0;
}
Experiment #2
This code will compile with no problems. When I compile and run it, I see the
following -