Search code examples
ctypesenumsinteger

sizeof inferring type long unsigned int instead of int in C


I have the following code

#include <stdio.h>

enum weekDays {
  Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
};

int main()
{
  const enum weekDays today = Wednesday;

  printf("Size of today is %d", sizeof(today));

  return 0;
}

But im trying to compile using gcc <filename> -o <output_name> I get the following error:

enum.c: In function 'main':
enum.c:36:18: warning: format '%d' expects argument of type 'int', but argument 2 has type 'long unsigned int' [-Wformat=]
   36 |   printf("Day %d", sizeof(today));
      |               ~^   ~~~~~~~~~~~~~
      |                |   |
      |                int long unsigned int
      |               %ld

Like the return type of sizeof is a long unsigned int instead of an integer

Also, i saw a few C tutorials an the code i have is working fine in those videos. I.E:

enter image description here


Solution

  • The sizeof operator evaluates to a value of type size_t, not int.

    The line

    printf("Size of today is %d", sizeof(today));
    

    will invoke undefined behavior, because the %d conversion format specifier requires an argument of type int, but you are instead passing an argument of type size_t (which happens to be equivalent to long unsigned int on your platform).

    That is why you are getting a warning message from the compiler.

    The correct conversion format specifier for size_t is %zu instead of %d:

    printf( "Size of today is %zu.\n", sizeof today );
    

    See the documentation for printf for further information.