如果表达式的中间结果溢出,它是未定义的行为吗? [英] Is it undefined behavior if the intermediate result of an expression overflows?

查看:59
本文介绍了如果表达式的中间结果溢出,它是未定义的行为吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是另一个 示例代码

#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. 我正确地认为#1 #2 会调用未定义的行为,因为中间结果 100 * 30000000 不会是否适合 int ?还是我看到的输出定义明确?

  1. Am I correct in thinking that #1 and #2 invoke undefined behavior because the intermediate result 100 * 30000000 does not fit into an int? 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屋!

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