Operating System - HP-UX
1820879 Members
4963 Online
109628 Solutions
New Discussion юеВ

Illegal piece of code (conditional operator)

 
Max_4
Frequent Advisor

Illegal piece of code (conditional operator)

Hi to all,

I've seen this code snippet before:

int main()
{
int x = 10;
int y = 80;
int z = 110;

x == 10 ? y = 20 : z = 40;

printf("x = %d, y = %d, z = %d\n", x, y, z);
}

Which I think it's illegal, because of the order of precedence...
I think that analyzing this expression:
x == 10 ? y = 20 : z = 40;
produces the following implied parenthesized evaluation.
I mean it's evaluated as if I had written the expression like this:
(x == 10 ? y = 20 : z)= 40
in the first place...

And as one can see the left hand side of this assignment expression is not an
lvalue (the result of this conditional expression is not an lvalue, is a value).

I think what would be legal is to have written this expression like this in
the first place:

x == 10 ? (y = 20 ): (y= 40);

Am I right with my findings??

Additionally I also think that this expression:

x == 10 ? (y = 20 ): (z = 40);

Written with only a set of parentheses in the 3rd operand
is also legal in ANSI C. I mean:

x == 10 ? y = 20: (z= 40); /* LEGAL */
x == 10 ? y = 20: z = 40; /* ILLEGAL */

I mean only the last set of parentheses is required (I think...)
Maybe, because the second operand 'y = 20'
is embedded within '?' and ':'
and then in that
case there's no ambiguity.

Any input will be highly appreciated...

Thank you very much in advance...

Max
4 REPLIES 4
Eugeny Brychkov
Honored Contributor

Re: Illegal piece of code (conditional operator)

Max,
why not to try? I believe it will work even without brackets. This is conditional operator, and everything before ? is treated as a condition (false/true), following text between ? and : or ; is treated as should be executed when condition is true and following text between : and ; is executed if condition is false
Eugeny
Tom Danzig
Honored Contributor

Re: Illegal piece of code (conditional operator)

x == 10 ? y = 20 : z = 40;

seems legal to me.


If X is equal to 10, then set y to equal 20; otherwise set z equal to 40

Sound kosher to me.
Eugeny Brychkov
Honored Contributor

Re: Illegal piece of code (conditional operator)

I checked with C rules and seems that priority is highest ==, then ?: and then =, so maybe you're right and it will not work as one wants!
Eugeny
Eugeny Brychkov
Honored Contributor

Re: Illegal piece of code (conditional operator)

I checked - it is not even compiled with "Lvalue required in function main" error. You're absolutely correct: last brackets are necessary
Eugeny