相关疑难解决方法(0)

为什么在C和C++中算术运算之前必须将short转换为int?

从我从得到的回答这个问题,看来C++继承了这一要求,对于转换shortint从C.执行算术运算时,我可以挑你的大脑,以为什么这是用C首先介绍?为什么不做这些操作short呢?

例如(取自评论中的dyp建议):

short s = 1, t = 2 ;
auto  x = s + t ;
Run Code Online (Sandbox Code Playgroud)

x将具有int类型.

c c++ int short integer-promotion

70
推荐指数
4
解决办法
8650
查看次数

在C表达式中发生整数溢出时会发生什么?

我有以下C代码:

uint8_t firstValue = 111;
uint8_t secondValue = 145;
uint16_t temp = firstValue + secondValue;
if (temp > 0xFF) {
    return true;
}
return false;
Run Code Online (Sandbox Code Playgroud)

这是替代实现:

uint8_t firstValue = 111;
uint8_t secondValue = 145;
if (firstValue + secondValue > 0xFF) {
    return true;
}
return false;
Run Code Online (Sandbox Code Playgroud)

第一个例子是显而易见的,uint16_t类型足够大以包含结果.当我clang在OS/X上使用编译器尝试第二个示例时,它正确返回true.那里发生了什么?是否有某种临时的,更大的类型来包含结果?

c integer-overflow integer-promotion

4
推荐指数
1
解决办法
1528
查看次数

标签 统计

c ×2

integer-promotion ×2

c++ ×1

int ×1

integer-overflow ×1

short ×1