为什么直接把值传给sizeof运算符,数据类型的大小不一样?

Why is the size of the data type different when the value is directly passed to the sizeof operator?

#include <stdio.h>
int main() {
    char a = 'A';
    int b = 90000;
    float c = 6.5;
    printf("%d ",sizeof(6.5));
    printf("%d ",sizeof(90000));
    printf("%d ",sizeof('A'));
    printf("%d ",sizeof(c));
    printf("%d ",sizeof(b));
    printf("%d",sizeof(a));
    return 0;
}

输出为:

8 4 4 4 4 1

为什么相同的值输出不同?

C 中的字符常量(与 C++ 相反)的类型为 int。所以这个调用

printf("%d",sizeof('A'));

输出4。即sizeof( 'A' )等于sizeof( int )

来自 C 标准(6.4.4.4 字符常量)

10 An integer character constant has type int....

另一方面(6.5.3.4 sizeof 和 alignof 运算符)

4 When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1.

因此,此表达式 sizeof( 'A' )sizeof 运算符的操作数具有 int 类型,而在此表达式 sizeof( a ) 中,a 声明为

char a = 'A';

操作数的类型为 char

注意这样的调用

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

使用不正确的转换格式说明符。你必须写

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

同样在上面的调用中使用了一个double类型的常量,而在这个调用中

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

变量 c 的类型为 float

如果第一次调用使用 float 类型的常量,则这些调用可能会得到相同的结果

printf("%zu",sizeof(6.5f));

常量和变量一样,有自己的类型:

  • 6.5 : double
  • 类型的浮点常量
  • 90000 : int 类型的整数常量(如果 int 是 32 位)或 long (如果 int 是 16 位)
  • 'A' :在 C 中类型为 int 且在 C++ 中类型为 char 的字符常量

打印出来的尺码就是以上型号的尺码。

此外,sizeof 运算符的结果类型为 size_t。因此,在打印时要使用的正确格式说明符是 %zu,而不是 %d.

因为这些值对 sizeof 无关紧要。这是类型的大小。

  • 字符常量是ints,不是chars。

  • 浮点常量默认为 doubles 除非你用 fl.

  • 作为后缀