Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the value of expression f() > g(), when f & g modify same global variable undefined or unspecified?

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).


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 ?

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

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) ?

And what about this one:

bool z = (x() > i++);  // undefined or unspecified now ?
like image 939
abi Avatar asked Mar 02 '15 18:03

abi


People also ask

What is the value of expression?

To evaluate an algebraic expression means to find the value of the expression when the variable is replaced by a given number. To evaluate an expression, we substitute the given number for the variable in the expression and then simplify the expression using the order of operations.

What is F and G in functions?

The notation of the function f with g is (f∘g)(x)=f(g(x)) and is read f of g of x . It means that wherever there is an x in the function f , it is replaced with the function g(x) . The domain of f∘g is the set of all x in the domain of g such that g(x) is in the domain of f .

What type of function is f/g x ))?

f of g of x is a composite function that is represented by f(g(x)) (or) (f ∘ g)(x). To find f(g(x)), substitute g(x) into f(x). To find the domain of f(g(x)), find the domain of both the inner function g(x) and the resultant function f(g(x)) and then compute the intersection.


1 Answers

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

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

like image 101
Mike Seymour Avatar answered Oct 27 '22 00:10

Mike Seymour