As explained by others, changing the value of const leads to undefined behavior, and you donβt need to say anything else - any result is possible, including complete nonsense or failure.
If you are interested in how this particular result happened, it is almost certainly related to optimization. Since you defined a as const , the compiler can substitute the value 40 that you assigned to it when you want; after all, its value cannot change, right? This is useful if you use a to determine the size of the array, for example. Even in gcc, which has an extension for arrays of variable size, it is easier for the compiler to allocate an array with a constant size. Once optimization exists, it is probably applied sequentially.
source share