Home > Enterprise >  Why is using assignments in ternary operator generating an error without parentheses? [duplicate]
Why is using assignments in ternary operator generating an error without parentheses? [duplicate]

Time:09-24

This is a code in C, which is generating this error:

error: lvalue required as left operand of assignment

Code:

  #include <stdio.h>

int main()
{
   int m =4 ; int n =5;
    int c=0;
    
m>n?c=40: c=20;    
 
 printf("%d",c);   
}

But when I use the brackets in ternary operator it's generating output without error.

#include <stdio.h>

int main()
{
   int m =4 ; int n =5;
    int c=0;
    
m>n?(c=40): (c=20);    
 
 printf("%d",c);   
}

Output: 20

Why is this happening?

CodePudding user response:

m>n?c=40: c=20;

Your expression is the same as below

(m > n ? c = 40 : c) = 20;
((m > n) ? (c = 40) : c) = 20;

which may make the error more obvious.

CodePudding user response:

You are using it wrong. Write

c = (m > n) ? 40 : 20;
  •  Tags:  
  • c
  • Related