vmc7001 vmc7001 - 3 months ago 17
C Question

"lvalue required as left operand of assignment" error - ternary operator

While compiling the code below I'm getting the error "lvalue required as left operand of assignment"

for(i=1;i<2n;i++){
for(((i<=n)?j=1:j=i);j<=i&&j>0;((i<=n)?j++:j--)){
printf("*");

}
printf("\n");}


Actually I was trying to print the pattern below using only two for loops

*
**
***
****
*****
****
***
**
*


and the error I'm getting is

pra.c:5:20: error: lvalue required as left operand of assignment
for(((i<=5)?j=1:j=i);j<=i&&j>0;((i<=5)?j++:j--)){
^


could someone help me.

Answer

The only thing wrong with the code as written is that you have 2n where you presumably should have 2*n.

Your compiler seems to have decided that in (i<=5)?j=1:j=i, the assignment operator on the right should bind less strongly than the conditional operator. This is incorrect and you should file a bug against the compiler. See operator precedence

An operand binds more tightly to an assignment operator on its right than to : on its left

I assume adding a pair of parentheses around j=i will make your code compile, although some consider it bad style to have assignment expressions as operands to the conditional operator, so a better thing to write is j = (i <= 5 ? 1 : i).