gpt4 book ai didi

c++ - C 和 C++ 中 sizeof 运算符的不同输出

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:48:35 25 4
gpt4 key购买 nike

C 和 C++ 中 sizeof() 运算符的不同输出。

在 C 中:

int main() 
{
printf("%zu\n", sizeof(1 == 1));
return 0;
}

输出:

4

在 C++ 中:

int main() 
{
std::cout << sizeof(1 == 1) << std::endl;
return 0;
}

输出:

1

问题:

  • 为什么输出不同?
  • sizeof 是否独立于操作系统或编译器?
  • 是否取决于语言?

最佳答案

根据 N1570草稿():

6.5.9 相等运算符

The == (equal to) and != (not equal to) operators are analogous to the relational operators except for their lower precedence. Each of the operators yields 1 if the specified relation is true and 0 if it is false. The result has type int.

因此,sizeof(1 == 1) 将返回等于 sizeof(int) 的值,实现定义并且在您的如果是 4


根据 N4296草稿():

5.10 相等运算符

The == (equal to) and the != (not equal to) operators group left-to-right. The operands shall have arithmetic, enumeration, pointer, or pointer to member type, or type std::nullptr_t. The operators == and != both yield true or false, i.e., a result of type bool.

因此,sizeof(1 == 1) 将返回等于 sizeof(bool) 的值,实现定义并且在您的如果它是 1

关于c++ - C 和 C++ 中 sizeof 运算符的不同输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45634466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com