Christian Westbrook Christian Westbrook - 1 year ago 62
C Question

Data Type Mismatch and Conflicting Compilers

I'm studying the basic concepts of the C Programming Language on a website called TutorialsPoint. Examples of source code on this website can include a "try it" button that opens up an on-line c programming environment with an on-line c compiler (GNU GCC version 4.7.2). In one example the sizeof() function is demonstrated. Here is the source code.

#include <stdio.h>
#include <limits.h>

int main() {

printf("Storage size for int : %d \n", sizeof(int));

return 0;

Link to the lesson: TutorialsPoint - C Data Types

When this program is compiled and executed within the on-line programming environment, the following output is produced:

"Storage size for int : 4"

When I attempt to compile the same code on my computer using the GNU GCC version 5.2.1, I receive the following error message:

gcc sizeofExample.c
sizeofExample.c: In function 'main':
sizeofExample.c:6:10: warning: format '%d' expects argument of type 'int',
but argument 2 has type 'long unsigned int' [-Wformat=]
printf("Storage size for int: %d \n", sizeof(int));

Here is my source code, just to be thorough:

#include <stdio.h>
#include <limits.h>

int main()
printf("Storage size for int : %d \n", sizeof(int));

return 0;

I understand that this error is the result of a data type mismatch between the %d [int data type] and the sizeof(int) [long unsigned int].

Why does my compiler detect a data type mismatch, while TutorialsPoint's on-line compiler does not?

Answer Source

sizeof produces a size_t result (an unsigned quantity which is usually 4 bytes on 32 bit systems, and 8 bytes on 64 bit systems). You should use an appropriate printf format code, in this case %zu (z means "width equivalent to size_t", u meaning "unsigned value"). That should work correctly on all systems (aside from a very few incredibly archaic systems that don't support the z size modifier).

The on-line compiler probably doesn't complain because either:

  1. It's not performing the in depth printf format code checking gcc does or
  2. It's a 32 bit compiler, and size_t and int are the same size (though differing in signedness) so there isn't a size mismatch there, while your local gcc is a 64 bit compiler, and the sizes differ.
  3. The compiler simply doesn't display warnings in order to keep output simple for beginners.

Note that gcc is only warning, not erroring out, so the code will finish compilation and run. Usually warnings indicate a problem though, so it was a good thing to investigate further.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download