EmZo Stark
EmZo Stark

Reputation: 51

Getting error "lvalue required as left operand of assignment"

I am a novice in C and having the following problem while compiling a simple code:

#include <stdio.h>

int main()
{
    int i, a, b;
    i = 3;
    a = b = 0;

    printf("Before: ");
    printf("%d %d\n", a, b);
    i == 3 ? a = 4 : a = 10; /* Line 9 */

    printf("After: ");
    printf("%d %d\n", a, b);
    return 0;
}

Gives me error:

#gcc some.c
In function ‘main’:
some.c:9: error: lvalue required as left operand of assignment

I cannot understand it. What am i doing wrong?

Upvotes: 3

Views: 761

Answers (6)

kiner_shah
kiner_shah

Reputation: 4641

a = (i == 3 ? 4 : 10);

Try this! :-)

Upvotes: 2

user8084014
user8084014

Reputation:

The ternary operator does not work like this. You should use parenthesis to give higher priority to the equality operator. Check the priority precedence. By default, equality operators have least priority.

Upvotes: 0

Neel Patel
Neel Patel

Reputation: 368

?: is a ternary operator.
ternary operator have higher precedence than '=' operator.
so 9th line of your code work like this..

    (i == 3 ? a = 4 : a) = 10;

you have to use parenthesis or modify your sentence.
you can replace your 9th line with either of following line..

    i == 3 ? a = 4 : (a = 10);

    a = i == 3 ? 4 : 10;

Upvotes: 2

lost_in_the_source
lost_in_the_source

Reputation: 11237

You need to assign outside the ternary operator, not inside of it, because the ternary operator binds tighter than assignment. So you should write

a = ((i == 3) ? 4 : 10);

What you wrote is equal to

(i == 3 ? a = 4 : a ) = 10;

In this code, an rvalue is being assigned to. This is the same error as writing

myfunc() = 16;

Cosmetic note: In this case it is better to use an if else statement instead of a conditional operator, because it is more clear here.

if (i == 3)
    a = 4;
else
    a = 10;

Upvotes: 2

Beka
Beka

Reputation: 97

Try this

if (i==3) a = 4; else a = 10;

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

This operator

i==3 ? a=4 : a = 10;

is equivalent to

( i==3 ? a=4 : a ) = 10;

Use instead

i==3 ? a=4 : ( a = 10 );

Upvotes: 7

Related Questions