5
#include <stdio.h>
int main()
{
  int a=3,b=4,g;
  a > b ? g = a : g = b ;
  printf("%d",g);
  return 0;
}

Why does the value of g not get printed? And compiler says lvalue required. What does it mean?

pouyan
  • 307
  • 1
  • 5
Satyam Garg
  • 156
  • 9
  • 1
    You've to change `a > b ? g = a : g = b ;` to `g = a > b ? a : b;` or `a > b ? g =a : (g = b);` – pouyan Jan 30 '16 at 12:17

2 Answers2

15

Due to higher precedence of operator ?: over =, the expression

a > b ? g = a : g = b;   

will be parsed as

(a > b ? g = a : g) = b;  

The expression (a > b ? g = a : g) will give an rvalue. The left operand of assignment (=) operator must be an lvalue1 (modifiable2).

Change

a > b ? g = a : g = b ;  

to

a > b ? (g = a) : (g = b);    

or

g = a > b ? a : b;

1. C11-§6.5.16/2: An assignment operator shall have a modifiable lvalue as its left operand.
2. §6.3.2.1/1: An lvalue is an expression (with an object type other than void) that potentially designates an object;64) if an lvalue does not designate an object when it is evaluated, the behavior is undefined. When an object is said to have a particular type, the type is specified by the lvalue used to designate the object. A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a const- qualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a const- qualified type.

haccks
  • 104,019
  • 25
  • 176
  • 264
0
  • Just replace your:

    a > b ? g = a : g = b ;
    

    with

    a > b ? (g = a) : (g = b) ;
    
  • Because precedance of Parentheses is higher.So if condition a > b is become true then value of a is assigned to g and if it fails then value of b is assigned to g.

Sagar Patel
  • 864
  • 1
  • 11
  • 22