How to write the expression a<=20?b=30:c=30; such that 30 is used only once?

Viewed 399

I'm following a book on c programming and encountered this example:

a<=20?b=30:c=30;

I just have to use the number 30 one time. The solution in the book was

((a<=20)?&b:&c)=30);

When I try to run this I get the following error:

lvalue required as left operand of assignment.

It seems like one of the parenthesis is missing there, but I don't know where.

Can you please tell me how I can fix this?

2 Answers

supposing a and b are numbers of the same type, just do

*((a <= 20) ? &b : &c) = 30;

getting a and b address it is needed to dereference (the '*') to have a lvalue

from @Vrintle remark note you can also do in C++

((a<=20)?b:c)=30;

the compiler knows the form is a lvalue so the value of b and c are not used but their reference

It seems like one of the parenthesis is missing there, but I don't know where.

in ((a<=20)?&b:&c)=30); the last ')' does not have corresponding '('

For starters in C this expression

a<=20?b=30:c=30

is equivalent to

( a<=20?b=30:c ) = 30

and the compiler will issue an error because the left operand of the assignment is not lvalue.

You have to write

a <= 20 ? b = 30 : ( c = 30 )

or for symmetry

a <= 20 ? ( b = 30 ) : ( c = 30 )

What you mean is the following

*( a <= 20 ? &b : &c ) = 30;

It is a trick of getting a reference to an object in the C meaning that is indirectly through a pointer to an object. The pointer itself is rvalue but dereferencing it you get lvalue of the pointed object.

In C++ you could write simply

( a <= 20 ? b : c ) = 30;

because in this case the operator returns lvalue.

There is a difference between C and C++ in the definition of the grammar of the conditional operator.

In C it is defined like (6.5.15 Conditional operator)

conditional-expression:
    logical-OR-expression
    logical-OR-expression ? expression : conditional-expression

while in C++ (C++ 14, 5.16 Conditional operator)

conditional-expression:
    logical-or-expression
    logical-or-expression ? expression : assignment-expression

So in C++ the original expression that is not compiled by the C compiler is valid

a <= 20 ? b = 30 : c = 30
Related