c++ - 为什么在sizeof()中添加两个变量类型会返回最大的变量大小值而不是它们的总和?

标签 c++ sizeof

#include <iostream>

using namespace std;

int main()
{
    int a;
    long b;

    cout<<sizeof(a+b);

    return 0;
}

输出为8(长变量的大小)。为什么不返回它们的总和?

最佳答案

the output is 8(size of a long variable)



由于整型促销

根据cppreference.com:

the ranks of all signed integer types are different and increase with their precision: rank of signed char < rank of short < rank of int < rank of long int < rank of long long int



因此,a + b会生成long,因为aint,而blong(long的秩大于int)。

因此,您具有sizeof(long),即 8

why it doesn't return their addition



您可能正在寻找sizeof(a) + sizeof(b);

关于c++ - 为什么在sizeof()中添加两个变量类型会返回最大的变量大小值而不是它们的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60968536/

相关文章:

c++ - 为什么这个数组的 sizeof() 是非法的?

c++ - 带维度的数组参数

c++ - 重载 [] 运算符

c++ - 为什么 mkdir 无法使用波浪号 (~)?

c++ - Log4Cxx sql server appender

c++ - constexpr 函数中的 For 循环无法使用 MSVC 19.23 进行编译

c++ - 为什么函数不知道数组大小?

在c中动态更改结构属性

c++ - 使用标准库在 C++11 中使用 std::tie 提取嵌套在元组中的元组

c - 为什么 malloc 在我请求 20 个字节时给我 8 个字节?