gpt4 book ai didi

c++ - 算术操作数类型转换

转载 作者:行者123 更新时间:2023-12-01 14:03:46 25 4
gpt4 key购买 nike

为什么在下面的代码中:

short a = 4;
char b = 2;
cout << sizeof(a/b);

sizeof(a/b) 是 4?为什么不是 2 作为短的尺寸?

最佳答案

4因为表达式的类型 a / bint而不是 short .
摘自 The C++ Programming Language 一书:

Before an arithmetic operation is performed, integral promotion is used to create ints out of shorter integer types.



所以,现在你的(较短的整数) ab操作数被提升为 int 类型.于是整个 a / b表达式变成 int和类型的大小 int很可能是 4您机器上的字节数。

sizeof您的情况下的运算符返回表达式类型的大小,即 int , 即 4 . sizeof运算符(operator)可以返回:
  • 型号尺寸
  • 表达式类型的大小

  • 这种类型转换不称为类型转换,而是整体提升。

    关于c++ - 算术操作数类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60764194/

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