This question already has an answer here:
I keep getting compile warnings but I don't know how to fix it:
'%d' expects argument of type 'int', but argument 2 has type 'long unsigned int' [
The program runs fine but I still get the compile warnings:
/* Sizeof.c--Program to tell byte size of the C variable */
#include <stdio.h>
int main(void) {
printf("\nA Char is %d bytes", sizeof( char ));
printf("\nAn int is %d bytes", sizeof( int ));
printf("\nA short is %d bytes", sizeof( short ));
printf("\nA long is %d bytes", sizeof( long ));
printf("\nA long long is %d bytes\n", sizeof( long long ));
printf("\nAn unsigned Char is %d bytes", sizeof( unsigned char ));
printf("\nAn unsigned int is %d bytes", sizeof( unsigned int));
printf("\nAn unsigned short is %d bytes", sizeof( unsigned short ));
printf("\nAn unsigned long is %d bytes", sizeof( unsigned long ));
printf("\nAn unsigned long long is %d bytes\n",
sizeof( unsigned long long ));
printf("\nfloat is %d bytes", sizeof( float ));
printf("\nA double is %d bytes\n", sizeof( double ));
printf("\nA long double is %d bytes\n", sizeof( long double ));
return 0;
}
sizeof
returnssize_t
you need to use%zu
for the format string instead of%d
. The type of unsigned integer ofsize_t
can vary (depending on platform) and may not be long unsigned int everywhere, which is covered in the draft C99 standard section6.5.3.4
The sizeof operator paragraph 4:Also note that using the wrong format specifier for
printf
is undefined behavior, which is covered in section7.19.6.1
The fprintf function, which also coversprintf
with respect to format specifiers says:Update
Visual Studio
does not support thez
format specifier:the correct format specifier in this case would be
%Iu
.i had the same problem in Linux. the same program runs without error in windows (means '%d' worked without error), but for linux i had to replace all the '%d' with'%lu' to run the program.
The compiler is warning you that you may suffer a loss of precision. That is, the format specifier that you're using to print a
sizeof
,%d
, is not capable of printing the full range ofsize_t
. Change%d
to%zu
and your warning will go away.