Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The most likely reason for <code>m</code> being <code>0</code> in your snippet is because you assign <code>m</code> to have this value in the body of your if-statement, but since the code contains <em>undefined behavior</em> no one can say that for sure.</p> <hr> <h2>The likely story about passing a <code>short*</code> when scanf expects an <code>int*</code></h2> <p>Assuming <code>sizeof(short) = 2</code> and <code>sizeof(int) == 4</code>.</p> <p>When entering your main function the stack on which the variables reside would normally look something like the below:</p> <pre><code> _ |short int (a) : scanf will try to read an int (4 bytes). |_ 2 bytes : This part of memory will most |int (n) : likely be overwritten | :.. | |_ 4 bytes |int (m) | | |_ 4 bytes </code></pre> <p>When you read a <code>%d</code> (ie. an <code>int</code>) into the variable <code>a</code> that shouldn't affect variable <code>m</code>, though <code>n</code> will most likely have parts of it overwritten.</p> <hr> <h2>Undefined Behavior</h2> <p>Though it's all a guessing game since you are invoking what we normally refer to as "<em>undefined behavior</em>" when using your scanf statement.</p> <p>Everything the standard doesn't guarantee is UB, and the result could be anything. Maybe you will write data to another segment that is part of a different variable, or maybe you might make the universe implode.</p> <p>Nobody can guarantee that we will live to see another day when UB is present.</p> <hr> <h2>How to read a <code>short int</code> using <code>scanf</code></h2> <p>Use <code>%hd</code>, and be sure to pass it a <code>short*</code>.. we've had enough of UB for one night!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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