gpt4 book ai didi

c - 整数溢出在 C 中是如何工作的?

转载 作者:太空宇宙 更新时间:2023-11-03 23:26:36 25 4
gpt4 key购买 nike

我对如何在定点环境中处理算术计算感到有点困惑。考虑以下代码行:

/* unsigned short is 16 bit.*/
unsigned short x = 1000;
unsigned short res;

/* Case1: The following yields correct result in res */
res = (x*544/100);

/* Case2: The following yields wrong result in res*/
res = (x*544); /* expected overflow here */
res = res/100;

所以,我的问题是:我明白为什么案例 2 会产生错误的结果。但 - 编译器在情况 1 中做了什么产生了正确的结果? - 案例 1 中的算术运算本质上不是一回事吗?除了,它分为两个语句? - 我可以期待不同编译器的不同行为吗?

最佳答案

这是由于将通常的算术转换应用于乘法操作数,然后应用于除法,这导致 short 为了计算目的被提升为更大的整数类型,然后在分配时转换为short

draft C99 standard6.5.5 Multiplicative operators 部分中说:

The usual arithmetic conversions are performed on the operands.

我们还需要注意整数常量544100 的类型为int,我们可以在问题 what are default integer values? 中找到有关原因的详细信息.

然后我们可以转到 6.3.1.8 通常的算术转换 部分,我们在以下段落结束:

Otherwise, the integer promotions are performed on both operands. Then the following rules are applied to the promoted operands:

我们最终得到以下规则:

Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.

所以计算的结果是一个int

使用 -Wcoversion 标志 gcc 但令人惊讶的是 clang 会产生警告:

warning: conversion to 'short unsigned int' from 'int' may alter its value [-Wconversion]
res = (x*544/100);
^

这会导致您在第一种情况下称为正确的结果,因为在您的第二种情况下所有计算都是以 int 的形式完成的,您会丢失来自乘法,因为您将它分配回 res,并且该值被转换为适合 short 的值。

关于c - 整数溢出在 C 中是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25814552/

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