Home > Enterprise >  Error showing in while using ternary operator l value required as left operand of assignment
Error showing in while using ternary operator l value required as left operand of assignment

Time:10-20

Showing error l value required as left operand of assignment

#include<stdio.h>
void main()
{
    int i,j,l,n,s;
    printf("Enter the number size you want to print :");
    scanf("%d",&n);
    for(i=-n;i<=n;i  )
    {
        (i<0)? l=-i:l=i;
        for(j=0;j<l 1;j  )
        { 
            printf("* ");
        } 
        printf("\n");
    }
}

i want to write this one in ternary operator

if(i<0)
        {
            l=-i;
        }
        else
        {
            l=i;
        }

CodePudding user response:

In C the conditional operator is defined the following way (6.5.15 Conditional operator)

conditional-expression:
    logical-OR-expression
    logical-OR-expression ? expression : conditional-expression

That is the last expression in the conditional operator does not accept the assignment operator because the assignment operator has a lower precedence than the conditional operator. So your statement

(i<0)? l=-i:l=i;

is equivalent to

( (i<0)? l=-i:l ) = i;

Instead you need to write

(i<0)? l=-i: ( l=i );

Opposite to C in C the conditional operator is defined the following way (C 17 Standard, 8.16 Conditional operator)

conditional-expression:
    logical-or-expression
    logical-or-expression ? expression : assignment-expression

So if to compile your program as a C program then this statement

(i<0)? l=-i:l=i;

will be valid.

In any case you could rewrite the operator the following way

l = i < 0 ? -i : i;

and this statement will be valid in C and C .

CodePudding user response:

(i<0)? l=-i:l=i;

change this line to

l=(i<0)?-i:i;
  • Related