Reputation: 101
Say you have x = exp1 + exp2 in c. It might be evaluated by first evaluating exp1 then exp2 and adding the results however it may evaluate exp2 first.
How do you find out which side is evaluated first? I would like to make x = 1/2 depending on which one was evaluated first.
Any ideas?
Upvotes: 4
Views: 150
Reputation: 213791
How do you find out which side is evaluated first?
Generally this is not specified by the standard. C11 6.5/3:
Except as specified later, side effects and value computations of subexpressions are unsequenced. 86)
...
86) In an expression that is evaluated more than once during the execution of a program, unsequenced and indeterminately sequenced evaluations of its subexpressions need not be performed consistently in different evaluations.
"Specified later" refers to a few special cases where the order of evaluation is specified, namely for the following operators: || && ?: ,
, which are all guaranteed to be evaluated left-to-right.
As we can see from the cited note, we can't even know if the same program will treat the same expression consistently. This is called unspecified behavior, which means that compiler will behave in one of several well-defined ways but we can never know or assume which way. You should always write your programs so that the order of evaluation does not matter.
If you wish to fool around with code that prints which order the compiler decided to evaluate a particular expression (this time), you could do:
#include <stdio.h>
int func(void)
{
static int x=0;
return x++;
}
int main (void)
{
printf("%d", func() << func());
}
This will either give 0<<1 == 0
(left-to-right) or 1<<0 == 1
(right-to-left). But such code has no practical purpose.
Upvotes: 0
Reputation: 399803
Okay, you can do it like this:
#include <stdbool.h>
#include <stdio.h>
static int first(int value)
{
static bool first = false;
if (!first)
{
first = true;
return value;
}
return 0;
}
int main(void)
{
const int x = first(1) + first(2);
printf("got %d\n", x);
}
On ideone.com, I got 1
.
Note that this proves nothing, since there is no defined behavior here. The C99 draft says (in 6.5 Expressions, paragraph 3):
The grouping of operators and operands is indicated by the syntax.72) Except as specified later (for the function-call
()
,&&
,||
,?:
, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.
Upvotes: 5