C triple expression expression does not work

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

Why is g not printed? And the compiler says lvalue . What does it mean?

+5
source share
2 answers

Due to the higher precedence of the ?: Operator ?: over = expression

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

will be analyzed as

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

The expression (a > b ? g = a : g) gives the value of r. The operator of the left operand of the job ( = ) must be lvalue 1 (modifiable 2 ).

Change

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

to

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

or

 g = a > b ? a : b; 

<sub> 1 . C11-Β§6.5.16 / 2: The assignment operator must have a modifiable value lval as its left operand.
2 . Β§6.3.2.1 / 1: The value lvalue is an expression (with an object type other than void) that potentially denotes an object ; 64) if the lvalue does not indicate the object when evaluating it, the behavior is undefined. When an object is of a specific type, the type is determined by the value l used to denote the object. The modifiable value of lvalue is an lvalue that does not have an array type, does not have an incomplete type, does not have a specific type of const, and if it is a structure or union, does not have any member (including recursively, any member or element of all contained aggregates or associations) with categorized type .

+15
source
  • Just replace:

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

    with

     a > b ? (g = a) : (g = b) ; 
  • Since the priority of the brackets is greater. Therefore, if the condition a > b becomes true, then the value of a is assigned to g, and if it fails, then the value of b is assigned to g.

0
source

Source: https://habr.com/ru/post/1241883/


All Articles