如果表达式的中间结果溢出,它是未定义的行为吗? [英] Is it undefined behavior if the intermediate result of an expression overflows?
问题描述
这个问题是另一个 示例代码
#include <iostream>
int main()
{
unsigned long b = 35000000;
int i = 100;
int j = 30000000;
unsigned long n = ( i * j ) / b; // #1
unsigned long m = ( 100 * 30000000 ) / b; // #2
std::cout << n << std::endl;
std::cout << m << std::endl;
}
输出
85
85
85
85
使用 g ++ -std = c ++ 11 -Wall -pedantic -O0 -Wextra
编译此代码会给出以下警告:
Compiling this code with g++ -std=c++11 -Wall -pedantic -O0 -Wextra
gives the following warning:
9:28:警告:表达式[-Woverflow]
问题
-
我正确地认为
#1
和#2
会调用未定义的行为,因为中间结果100 * 30000000
不会是否适合int
?还是我看到的输出定义明确?
Am I correct in thinking that
#1
and#2
invoke undefined behavior because the intermediate result100 * 30000000
does not fit into anint
? Or is the output I am seeing well-defined?
为什么只对#2
发出警告?
推荐答案
是的,这是未定义的行为,如果 unsigned long
是64位类型,则得到的结果通常不相同.
Yes, it is undefined behaviour, and the result you get is usually¹ different if unsigned long
is a 64-bit type.
¹是UB,所以没有保证.
¹ It's UB, so there are no guarantees.
这篇关于如果表达式的中间结果溢出,它是未定义的行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!