sizeof(int(123)) 是什么意思?

What does sizeof(int(123)) mean?

我很惊讶为什么下面的代码可以编译:

#include <stdio.h>

int main(){
    printf("%lu",sizeof(int(123)));
    return 0;
}

输出为4,这里的(123)是什么意思?

而且我发现这行代码可以用g++编译,但是gcc不行,请问是什么原因?

这是 C++,int(123) 是对 int 的函数样式转换。这当然毫无意义,因为 123 无论如何都是 int 类型的文字。

函数式转换不是 C 的一部分,这就是它不能使用 C 编译器构建的原因。

为了回答更多的问题,发生的事情是运算符 sizeof 在编译时评估其参数的大小(在 chars 中)。参数是 int 类型,因此您在平台上输出 int 的大小为 4.

您也可以只使用普通的 sizeof 123,它将在 C 中构建,或者 sizeof (int) 来明确类型而不是从值中派生类型。请注意,括号是参数的一部分(类型名称写成 C 风格的转换),sizeof 不是函数。

sizeof 是一个 关键字 ,但它是一个编译时运算符,用于确定变量或数据类型的大小(以字节为单位)。

sizeof运算符可用于获取类、结构、联合和任何其他用户定义数据类型的大小。

使用sizeof的语法如下:

sizeof(数据类型) 其中数据类型是所需的数据类型,包括 类、结构、联合和任何其他用户定义的数据类型。

尝试以下示例以了解 C++ 中可用的所有 sizeof 运算符。将以下 C++ 程序复制并粘贴到 test.cpp 文件中并编译 运行 这个程序。

#include <iostream>
using namespace std;

int main() {
   cout << "Size of char : " << sizeof(char) << endl;
   cout << "Size of int : " << sizeof(int) << endl;
   cout << "Size of short int : " << sizeof(short int) << endl;
   cout << "Size of long int : " << sizeof(long int) << endl;
   cout << "Size of float : " << sizeof(float) << endl;
   cout << "Size of double : " << sizeof(double) << endl;
   cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
   return 0;
}

上面的代码编译执行后,会产生如下结果,不同机器可能不同:

Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4

int(123) 是使用显式类型转换的表达式。

来自 C++ 标准(5.2.3 显式类型转换(函数符号))

1 A simple-type-specifier (7.1.6.2) or typename-specifier (14.6) followed by a parenthesized expression-list constructs a value of the specified type given the expression list. If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4)...

至于 sizeof 运算符 then (C++ STandard, 5.3.3 Sizeof)

1 The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is an unevaluated operand (Clause 5), or a parenthesized type-id...

因此在这个表达式中

sizeof(int(123))

使用了 int 类型的整型文字到 int 类型的显式转换(这没有多大意义),并将 sizeof 运算符应用于产生结果的表达式size_t.

类型

实际上这个表达式等同于

sizeof(int)

或者在这种特殊情况下

sizeof(123)

因为整数文字 123 的类型为 int.

函数符号显式转换的形式只在C++中有效。在 C 中没有这样的转换符号。