Friday, 15 June 2012

c - Printing short int using various format specifiers -



c - Printing short int using various format specifiers -

please have @ 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); homecoming 0; }

it gave output :

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

in lastly line why s = 4294967295 instead of s = -1 through this question came know in c when variable gets promoted, value remains constant.

s beingness promoted int, here 4 byte type. happening in 3 cases. in first two, int printf() expect, format specifier type passed int. in lastly case, have given format specifier expects 8-byte type.

this invoking undefined behaviour.

in case appears have read zeros in upper bytes of value, zero-extending 64-bits value sign-extended 32-bits. can't depend on results of doing - might reading memory or register not consistently initialised. tomorrow different.

the promotion of arguments not dependent on format string - must ensure pass right arguments format have specified. int not promoted long. need convert yourself.

a smart compiler ought give warning this.

c casting integer-arithmetic

No comments:

Post a Comment