2

I am new to C Language. I have a doubt regarding the lvalue Error. As I can understand, We get an lvalue Error when there is no permanent-address-bearing-variable to store the Rvalue. Here I can see a variable on the left side. But still, I get lvalue error. Can somebody please clear my concepts of lvalue or the operator used.

#include"stdio.h"
void main()
{
int x=10,a;
x<0 ? a = 100 : a = 1000;
printf(" %d",a);
}

Thank You.

0

5 Answers 5

7

It would be

a = x < 0 ? 100 : 1000;

Assignment has lower precendence than ternary operator so it messes up.

Or this would also work (keeping in mind what I said earlier)

x<0 ? (a = 100) : (a = 1000);

How the compiler saw yours?

((x<0) ? a = 100 : a) = 1000;

It's clear now why compiler complained about lvalue.(ternary operator generated a rvalue and assignment operator expects a lvalue to the left of it) Isn't it?

0
#include"stdio.h"
void main() {
   int x=10,a;
   a = x<0 ? 100 : 1000;
   printf(" %d",a);
}

The ternary operator is used differently.

x = ( condition )? val1 : val2;

  1. Here, condition could be anything.

  2. Type of val1 and val2 should be same.

0

You can assign value like this.

a = x<0 ? 100 : 1000;
0

An lvalue (locator value) represents an object that occupies some identifiable location in memory (i.e. has an address).

Let's take example

int var;
var = 4;

An assignment expects an lvalue as its left operand, and var is an lvalue, because it is an object with an identifiable memory location. On the other hand, the following are invalid:

4 = var;       // ERROR!
(var + 1) = 4; // ERROR!

Neither the constant 4, nor the expression var + 1 are lvalues (which makes them rvalues). They're not lvalues because both are temporary results of expressions, which don't have an identifiable memory location (i.e. they can just reside in some temporary register for the duration of the computation). Therefore, assigning to them makes no semantic sense - there's nowhere to assign to.

0

You are not assigning back the result from the operation to a variable for storing it. You have declared int a but never used it.

a = x < 0 ? 100 : 1000;

Also, as a side note, assignment = has lower precedence than ternary operator so the warning has generated due to it.

Not the answer you're looking for? Browse other questions tagged or ask your own question.