1

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.

Pranav Jituri
  • 823
  • 1
  • 11
  • 25
  • 2
    All the answers below are correct, but I'm 99% sure that windows lacks "%zu" (because it intentionally refused to support C99) – loreb Jan 15 '14 at 18:02

3 Answers3

4

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]
Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
  • Do you have any resource in mind where I could read more about this? Or could you explain a bit more? :) – Pranav Jituri Jan 15 '14 at 18:07
  • This code worked in the Linux environment yesterday but today when I am trying this in Visual Studio, using the `%zu` format specifier, it is not giving the output as 4 bytes but rather printing `zu` as output. Any ideas why this is happening? – Pranav Jituri Jan 16 '14 at 04:24
  • Keep in mind that MSVC doesn't support C99. – haccks Jan 16 '14 at 11:24
  • So doesn't that make the code run only on one environment? Anyway to resolve this? o.O Also is there any way I can contact you directly? :| – Pranav Jituri Jan 16 '14 at 11:53
  • On Windows you can use `%u` specifier. As `size_t` is implementation defined, I think on Windows it is of type `unsigned int`. – haccks Jan 16 '14 at 12:40
1

sizeof return size_t and not int

Use %zu in printf

Digital_Reality
  • 4,488
  • 1
  • 29
  • 31
0

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

Use:

printf("\nThe Size Of Integer A Is = \t%zu", sizeof(a));
manuell
  • 7,528
  • 5
  • 31
  • 58