表达式f()的值是否> g(),当f& g修改未定义或未指定的相同全局变量? [英] Is the value of expression f() > g(), when f & g modify same global variable undefined or unspecified?

查看:53
本文介绍了表达式f()的值是否> g(),当f& g修改未定义或未指定的相同全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:由用户 ecatmur 标记,它是(尽管问题是关于C99的,但对于C ++而言,答案是不变的)。答案是:未指定(对于这两种情况)。

UPDATE: As marked by user ecatmur, it's a duplicate of In C99, is f()+g() undefined or merely unspecified? (although the questions asks about C99, but answer is unchanged for C++). And the answer is: unspecified (for both cases).

考虑使用C ++ 14个代码段:

Consider following C++14 code fragment:

int i = 0;
int x() { i++; return i;}
int y() { i++; return i;}
bool z = (x() > y());  // unspecified or undefined ?

z 的值仅仅是未指定,还是这种未定义的行为?

Is the value of z merely unspecified, or is this undefined behavior ?

根据我的理解(如果我错了,请更正),该表达式为: i ++> i ++ 将是未定义的行为,因为我们在一对序列点之间两次对同一变量进行了突变,但是上面的情况呢(突变发生在单独的函数中)呢?

As per my understanding (please correct if I am wrong), an expression of the kind: i++ > i++ will be undefined behavior, as we are mutating same variable twice between a pair of sequence points, but what about the case above (where mutation happen in separate functions) ?

这个呢?

bool z = (x() > i++);  // undefined or unspecified now ?


推荐答案

在两种情况下,该值均未指定,但行为定义明确。如[intro.exececution] 1.9 / 15中所指定,函数调用相对于调用它们的表达式中的其他评估不确定地排序:

In both cases, the value is unspecified, but behaviour is well-defined. Function calls are indeterminately sequenced with respect to other evaluations in the expression that calls them, as specified in [intro.exececution] 1.9/15:


相对于被调用函数的执行,不确定地对调用函数主体中执行的每个评估(包括其他函数调用)进行未确定顺序的所有

Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function

因此,对 i 的所有访问都按顺序进行,给出了明确的行为,但是顺序不确定,给出了一个未指定的值。

So all accesses to i are sequenced, giving well-defined behaviour, but the sequence is indeterminate, giving an unspecified value.

这篇关于表达式f()的值是否> g(),当f& g修改未定义或未指定的相同全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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