Printing short int using different format specifiers

Please take a look at this code:

#include <stdio.h>
int main(void)
{
short s = -1;

printf("sizeof(short) = %lu\n", sizeof(short));
printf("sizeof(int) = %lu\n", sizeof(int));
printf("sizeof(long) = %lu\n", sizeof(long));
printf("s = %hd\n", s);
printf("s = %d\n", s);
printf("s = %ld\n", s);

return 0;
}  

      

It gave the result as:

sizeof(short) = 2  
sizeof(int) = 4  
sizeof(long) = 8  
s = -1  
s = -1  
s = 4294967295  

      

On the last line why, s = 4294967295

instead of s = -1

like through this question, I found out that In C, when a variable gets promoted, its value remains constant.

+3


source to share


2 answers


s

promotes to int

, which is a 4-byte type here. This happens in all three cases. In the first two cases, it int

will be expected printf()

because the format specifier is of the type to be passed as int

. However, in the latter case, you provided a format specifier that expects an 8 byte type.

This causes undefined behavior.

In your case, it looks like there were zeros read in the upper bytes of the values, effectively zeroing to 64-bit values ​​that were already signed-expanded to 32 bits. However, you cannot depend on the results of this - it could be a memory read or a register that is not always initialized. It might be different tomorrow.



Argument promotion is independent of the format string - you must always ensure that you pass the correct arguments for the format you specify. Thus, int

it will not rise to long

. You need to convert it yourself.

A smart compiler should warn you about this.

+6


source


The variable is not incremented until called printf("s = %ld\n", s);

. The correct way to promote it to the end is printf("s = %ld\n", (long) s);

.



+1


source







All Articles