Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's going to be a bit of a guess why the const matters, but one can make a reasonable assumption.</p> <p>Variables with block scope, such as <code>result</code> 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 <code>const</code> matters, in this case. In the end, it's the compilers right to use what it thinks works best.</p> <p>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.</p> <p>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 <code>const</code>.</p> <p>Now as it happens you pass the wrong format specifier to <code>printf(...)</code>, namely <code>%u</code> instead of <code>%ld</code>. 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. <code>printf(...)</code> could for instance stumble across your uncopied <code>result</code>, 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 <code>printf(...)</code> just finds garbage.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload