It's going to be a bit of a guess why the const matters, but one can make a reasonable assumption.
Variables with block scope, such as result
can be allocated to a register or put on the stack. There are many factors that influence whether a register is used. It's quite possible that const
matters, in this case. In the end, it's the compilers right to use what it thinks works best.
Similarly, arguments to functions can be passed in registers or on the stack. As functions are often compiled seperately, their interface (i.e. declaration) dictates which argument goes where. printf(...) is a special case, as it can be called with different types arguments. As a result, what data ends up where will vary, and you need to tell printf(...) what to expect.
Now when passing a variable to a function, the compiler usually has to copy it. From a register to the stack, one register to another, etcetera, there are quite a few variations possible. As I indicated, the source location may differ depending on the presence or absence of const
.
Now as it happens you pass the wrong format specifier to printf(...)
, namely %u
instead of %ld
. This can cause printf(...) to look in the wrong place to get its data - perhaps in a register instead of the stack, or the other way around. Such an action can cause quite surprising results. printf(...)
could for instance stumble across your uncopied result
, or the random old values in some register. It seems that in the non-const case it happens to find the correct value (even though it might have found it in the wrong place), whereas in the const case printf(...)
just finds garbage.