short int a,b,c;
scanf("%d%d",&a,&b);
c = a + b;
printf("%d %d %d",a,b,c);
Input: 5 8
Output: 0 8 8
Why is the value of a 0? Can any one explain this?
Platform — GCC ubuntu 10.04
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
scanfwith a"%d"format requires anint*argument. You’re giving it ashort int*argument, thus your program’s behavior is undefined.If you actually want to know why you’re getting the results you’re getting, I can speculate on that, but it’s much easier just to correct your code:
You can continue to use
"%d"forprintf, since theshort intarguments are promoted toint. You could use"%hd"withprintf, but it’s not necessary. (There is no similar promotion ofshort int*arguments toint*.)You can safely stop reading here.
The following is some speculation about what’s probably happening in your incorrect code. This is not a solution; the solution is to correct your code so it does what you want it to do. But might be instructive to see just how incorrect code can misbehave.
Assume
shortis 16 bits andintis 32 bits, which is typical. The first"%d"in the format string tellsscanfto read a value (you gave it5) and store it into a 32-bit int pointed to by the second argument,&a. Sinceais only 16 buts, it will store half the 32-bit value inaand the other half in some adjacent chunk of memory. The second"%d"does the same thing with&b; it stores half of the 32-bit representation of8inb, and the other half somewhere else.Based on your output, it appears that the second
"%d"causedscanfto store the low-order 16 bits of the value8inb, and the high-order 16 bits (with value 0) ina, overwriting the value stored by the first"%d". Note that the high-order 16 bits from the first"%d"were probably stored somewhere else, perhaps clobbering some other variable or perhaps writing to some otherwise unused memory.So the result is that you’ve stored 0 in
aand 8 inb, which explains the output you’re getting.All this is very speculative, and many many other results are possible. This kind of analysis is useful only for tracking down the behavior of incorrect code, with the goal of correcting it. Writing code that deliberately takes advantage of this kind of thing is an extraordinarily bad idea. The language says absolutely nothing about what incorrect code like this will do; its behavior can vary wildly on different systems, with different compiler settings, or even depending on the phase of the moon.