sizeof 推断类型 long unsigned int 而不是 C 中的 int

gop*_*lay 1 c enums types integer

我有以下代码

#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;
}
Run Code Online (Sandbox Code Playgroud)

但我尝试使用编译时gcc <filename> -o <output_name>出现以下错误:

#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;
}
Run Code Online (Sandbox Code Playgroud)

就像返回类型sizeof是 long unsigned int 而不是整数

另外,我看了一些 C 教程,我的代码在这些视频中运行良好。IE:

在此输入图像描述

And*_*zel 5

sizeof运算符计算出类型为 的值size_t,而不是int

线路

printf("Size of today is %d", sizeof(today));
Run Code Online (Sandbox Code Playgroud)

将调用未定义的行为,因为%d转换格式说明符需要类型的参数int,但您传递的是类型的参数size_t(这恰好相当于long unsigned int您的平台上的参数)。

这就是您从编译器收到警告消息的原因。

正确的转换格式说明符是size_t%zu不是%d

printf( "Size of today is %zu.\n", sizeof today );
Run Code Online (Sandbox Code Playgroud)

请参阅文档以printf获取更多信息。