Output data type of sizeof() operator

  • A+
Category:Languages

I am using Ubuntu 16.04.5 with gcc version 5.4.0

I was playing with sizeof() operator, wrote the code below:

#include <stdio.h>  int main(int argc, char *argv[]){          long int mylint = 31331313131.1313;          printf("size of long int is %d/n", sizeof(mylint));         printf("size of long int is %d/n", sizeof(long int));          return 0; } 

I tried to compile using gcc -o ... ... command and was expecting:

size of long int is 8 size of long int is 8 

But I got the following error:

fl_double_lint.c: In function ‘main’: fl_double_lint.c:11:9: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]    printf("size of long int is %d/n", sizeof(mylint));          ^ fl_double_lint.c:12:9: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]   printf("size of long int is %d/n", sizeof(long int)); 

When I use %ld instead it works as expected. Why sizeof() is not working with %d? (Why 'long unsigned int' but not 'int'?)

 


The sizeof operator evaluates to a value of type size_t. This type is unsigned and typically larger than an int, which is why you get the warning.

The proper type modifier for size_t is %zu:

printf("size of long int is %zu/n", sizeof(mylint)); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: