Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C ternary expression-statement not working [duplicate]

Tags:

c

conditional

#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?

like image 427
sgewraks Avatar asked Jan 30 '16 12:01

sgewraks


1 Answers

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.

like image 197
haccks Avatar answered Sep 30 '22 02:09

haccks