The most likely reason for m
being 0
in your snippet is because you assign m
to have this value in the body of your if-statement, but since the code contains undefined behavior no one can say that for sure.
The likely story about passing a short*
when scanf expects an int*
Assuming sizeof(short) = 2
and sizeof(int) == 4
.
When entering your main function the stack on which the variables reside would normally look something like the below:
_
|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
When you read a %d
(ie. an int
) into the variable a
that shouldn't affect variable m
, though n
will most likely have parts of it overwritten.
Undefined Behavior
Though it's all a guessing game since you are invoking what we normally refer to as "undefined behavior" when using your scanf statement.
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.
Nobody can guarantee that we will live to see another day when UB is present.
How to read a short int
using scanf
Use %hd
, and be sure to pass it a short*
.. we've had enough of UB for one night!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…