Anagh Basak
Anagh Basak

Reputation: 147

What is the cause of the lvalue error in the below mentioned code?

#include <stdio.h>
int main(void){
   int n = 0, y = 1;
   y == 1 ? n = 0 : n = 1;
   if (n)
       printf("YES");
   else
       printf("NO");
   return 0;
  }

Can some one explain why does the line with the ternary operator give a lvalue error. I have a very abstract idea of what lvalue is. Let me give my abstraction, correct me if I am wrong. lvalue is typically the address or we can say the variable where we store a constant value and the value of a variable or a constant is a rvalue. But I don't understand why is there an lvalue error in the assignment part of the ternary operator which states n = 0 : n = 1. It would be really helpful if I could get a proper understanding of what is wrong with my code.

Upvotes: 2

Views: 110

Answers (2)

Barmar
Barmar

Reputation: 780871

The reason is that the ternary operator has higher precedence than assignment. So the expression is parsed as if you'd written:

(y == 1 ? n = 0 : n) = 1;

This is not a valid assignment because the result of the conditional operator is an rvalue, not an lvalue, so you can't assign to it.

You can solve the problem by adding parentheses around the assignments.

y == 1 ? (n = 0) : (n = 1);

But since you're assigning to the same variable, the more normal way to write this would be:

n = y == 1 ? 0: 1;

You can also take advantage of the fact that the result of a comparison operator is a boolean, either 0 or 1, so you can write simply:

n = y != 1;

Upvotes: 1

dbush
dbush

Reputation: 223739

The ternary operator ?: has higher precedence the assignment operator =. So your expression parses as:

(y == 1 ? n = 0 : n) = 1;

This gives you an expression on the left side of the assignment that is not an lvalue and therefore not assignable.

The ternary operator evaluates to either the value of the second part or the value of the third part, and these values are what you want to assign to n, so you could instead write it as:

n = y == 1 ? 0 : 1;

Or you could invert the condition and get rid of the ternary entirely:

n = y != 1;

Upvotes: 6

Related Questions