f



Order of evaluation of the operands is unspecified nature?

C compiler gives wrong behavior(code) if I compile the below conditional expression.

Compiler parser evaluates the operations in the below order:
if ( (a) || (b && c && d) == 1 )
1. operation &&
2. operation &&
3. operation ==
4. operation ||

void TestCode(void)
{
	if ( (a) || (b && c && d) == 1 )
	{
		i = 2;

	}
	else
	{
		i = 4;
	}
}


Here the coder's intention is to compare the result of logical operations with == 1.
However there is a chance that the compiler behaves wrongly due to of evaluation of the operands and not specified clearly by the coder.

If the coder uses parentheses () at the required operations ( ((a) || (b && c || d)) ) then the compiler job is easier. In that case, Compiler gives expected behavior.

If parentheses added then Compiler parser evaluates the operations in the below order:
if ( (a) || (b && c && d) == 1 )
1. operation &&
2. operation &&
3. operation ||
4. operation ==


Let's consider what ANSI standard says:

6.5.16 Assignment operators

The order of evaluation of the operands is unspecified. If an attempt is made to modify the result of an assignment operator or to access it after the next sequence point, the behavior is undefined.


As per ANSI standard I understand that this given conditional
expression falls under "undefined behavior" category and therefore the
compiler behaves wrongly.

Please let me know expert views or any useful links to refer. Thanks.

Regards,
Gsrm

[No, this is not undefined behavior.  I would look at paragraph 3 of
section 6.5 and at sections 6.5.9, 6.5.13, and 6.5.14, which reveal
that == has higher precedence than && and ||. -John]
0
gsrm01
7/30/2016 1:20:01 PM
comp.compilers 3310 articles. 0 followers. Post Follow

0 Replies
258 Views

Similar Articles

[PageSpeed] 54

Reply: