Related articles |
---|
Order of evaluation of the operands is unspecified nature? gsrm01@gmail.com (2016-07-30) |
From: | gsrm01@gmail.com |
Newsgroups: | comp.compilers |
Date: | Sat, 30 Jul 2016 06:20:01 -0700 (PDT) |
Organization: | Compilers Central |
Injection-Info: | miucha.iecc.com; posting-host="news.iecc.com:2001:470:1f07:1126:0:676f:7373:6970"; logging-data="89571"; mail-complaints-to="abuse@iecc.com" |
Keywords: | C, question, comment |
Posted-Date: | 30 Jul 2016 10:12:25 EDT |
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]
Return to the
comp.compilers page.
Search the
comp.compilers archives again.