the code is as follows:
#include <stdio.h>
main()
{
int m=123;
int n = 1234;
short int a;
a=~0;
if((a>>5)!=a){
printf("Logical Shift\n");
m=0;
}
else{
printf("Arithmetic Shift\n");
m=1;
}
scanf("%d",&a);
printf("%d\n", m);
}
after the line scanf("%d",&a); the value of m becomes 0.
I know it may be caused by the scanf: a’s type is short and the input’s type is int. But How can this affect the value of m ?
Thanks a lot !
The most likely reason for
mbeing0in your snippet is because you assignmto 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 anint*Assuming
sizeof(short) = 2andsizeof(int) == 4.When entering your main function the stack on which the variables reside would normally look something like the below:
When you read a
%d(ie. anint) into the variableathat shouldn’t affect variablem, thoughnwill 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 intusingscanfUse
%hd, and be sure to pass it ashort*.. we’ve had enough of UB for one night!