Both programs execute statements int *b; b = &a; *b = 200;
which invokes undefined behaviour because a
is a const int
and therefore shouldn't be modified. There is no right answer (expected output) — both crashing and not crashing are acceptable results, as is printing 10
or 200
(or lemons and oranges
— though that's a little unlikely to happen).
Don't execute anything that causes undefined behaviour!
Your compiler should be complaining; heed its warnings. If it isn't complaining, get a better compiler.
The difference is that the static const int a = 10;
variable is placed in a readonly segment (probably part of the text segment, though it really doesn't matter), so the system can spot when you write to it and causes the crash. On the other hand, const int a = 10;
is placed on the stack, and the stack is modifiable, so you don't get a crash.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…