0

In this below code:

#include<stdio.h>
int main(void)
{
    printf("%d",sizeof(int));
    return 0;
}

When compiled on gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4 compiler it gives warning:

format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=] printf("%d",sizeof(int));

Why I am getting this warning? Is it that return type of sizeof is 'long unsigned int' ?

When I replaced '%d' with '%ld' the warning went.

Danh
  • 5,916
  • 7
  • 30
  • 45
Shubham S. Naik
  • 341
  • 1
  • 4
  • 14
  • `sizeof` is an operator, not a function. – Chirality Nov 25 '16 at 06:01
  • This question is answered here: http://stackoverflow.com/questions/24797843/why-is-sizeofint-less-than-1 – MayurK Nov 25 '16 at 06:03
  • 2
    To avoid the warning you have to cast the value to int. It's like when you define your own sizeof() operator , you need a cast something like this, #define my-sizeof(type)(int*)(&type+1)-(int*)(&type) – lazyborg Nov 25 '16 at 06:05
  • @lazyborg: your macro won't work for both `my_sizeof(int)` and `my_sizeof(v)` (with some `int v;` variable) and `my_sizeof(2)`; in other words, the `sizeof` operator is genuinely needed. – Basile Starynkevitch Nov 25 '16 at 06:14

1 Answers1

14

The sizeof operator is processed at compile time (and can be applied on both types and expressions). It gives some constant* of type size_t. On your system (and mine Debian/Linux/x86-64 also) sizeof(int) is (size_t)4. That size_t type is often typedef-ed in some type like unsigned long (but what integral type it actually is depends upon the implementation). You could code

printf("%d", (int)sizeof(int));

or (since printf understands the %zd or %zu control format string for size_t)

printf("%zu", sizeof(int));

For maximum portability, use %zu (not %ld) for printing size_t (because you might find systems or configurations on which size_t is unsigned int etc...).

Note *: sizeof is always constant, except for VLA

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547