C分配给较大宽度整数时的整数溢出行为 [英] C integer overflow behaviour when assigning to larger-width integers

查看:147
本文介绍了C分配给较大宽度整数时的整数溢出行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在C中执行以下代码:

If I execute the following code in C:

#include <stdint.h>

uint16_t a = 4000;
uint16_t b = 8000;

int32_t c = a - b;

printf("%d", c);

它正确打印-4000作为结果。但是,我有点困惑:从另一个减去一个更大的无符号整数应该不会有算术溢出?这里有什么规则?

It correctly prints '-4000' as the result. However, I'm a little confused: shouldn't there be an arithmetic overflow when subtracting a larger unsigned integer from the other? What casting rules are at play here? This question seems a bit noobish, so any references would be greatly appreciated.

推荐答案

这个问题实际上有点复杂。算术表达式的操作数使用特定规则进行转换,您可以在的第3.2.1.5节中查看标准(C89)。在你的情况下,答案取决于类型 uint16_t 是什么。如果它小于 int ,说 short int ,那么操作数被转换为 int 并且您获得-4000,但在16位系统上, uint16_t 可以是 unsigned int ,并且转换为带符号类型不会自动发生。

The issue is actually somewhat complicated. Operands of arithmetic expressions are converted using specific rules that you can see in Section 3.2.1.5 of the Standard (C89). In your case, the answer depends on what the type uint16_t is. If it is smaller than int, say short int, then the operands are converted to int and you get -4000, but on a 16-bit system, uint16_t could be unsigned int and conversion to a signed type would not happen automatically.

这篇关于C分配给较大宽度整数时的整数溢出行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆