Question

I am getting a warning warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat]

I am writing a very basic program which gives the size of the data type but in the Linux environment I am getting this warning whereas in Visual Studio, the program works without any warning. The source code is as below :-

#include<stdio.h>

int main()
{

 int a;
 printf("\nThe Size Of Integer A Is = \t%d", sizeof(a));

return 0;
}

Answer will be appreciated and also can anyone tell me a proper way of solving such kind of warnings as I am new to this C and it's standard.

Was it helpful?

Solution

sizeof returns size_t type. Use %zu specifier to print the value of sizeof.

printf("\nThe Size Of Integer A Is = \t%zu", sizeof(a));    

C11 6.5.3.4 The sizeof and _Alignof operators:

5 The value of the result of both operators is implementation-defined, and its type (an unsigned integer type) is size_t, defined in <stddef.h> (and other headers).

NOTE: As loreb pointed out in his comment that when you will compile your code in Windows, then most probably you will get the warning like:

[Warning] unknown conversion type character 'z' in format [-Wformat]
[Warning] too many arguments for format [-Wformat-extra-args]

OTHER TIPS

sizeof return size_t and not int

Use %zu in printf

In C99 the correct format for a size_t variable is %zu.

Use:

printf("\nThe Size Of Integer A Is = \t%zu", sizeof(a));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top