C Programming - Control Instructions - Discussion

Discussion Forum : Control Instructions - Point Out Errors (Q.No. 9)
9.
Point out the error, if any in the program.
#include<stdio.h> 
int main()
{
    int a = 10, b;
    a >=5 ? b=100: b=200;
    printf("%d\n", b);
    return 0;
}
100
200
Error: L value required for b
Garbage value
Answer: Option
Explanation:

Variable b is not assigned.

It should be like:

b = a >= 5 ? 100 : 200;

Discussion:
34 comments Page 2 of 4.

Ajeet said:   1 decade ago
The conditional operator (?:) always return either true part or false part. Lvalue means legal left value. There no need of Lvalue in conditional operator so the program executes successfully and gives output 100;.

Praveen said:   1 decade ago
@Mani

The program which Aloke has posted works even though the expression a >=5 ? (b=100): (b=200); is not assigned to any value .. Would you please explain us in detail if you are clear with the concept ?

Prabhanjan mishra said:   10 years ago
I have compiled on the same code in Microsoft Visual C++ then the output will be 100 because the logic behind this is.

If b>5; then b=100.

Otherwise if b should be 200.

(condition) ? true : false.
(1)

Nitesh said:   1 decade ago
It can also be like this.

#include<stdio.h>
int main()

{
int a = 10, b;
a>=5?(b=100):(b=200);
printf("%d\n", b);
return 0;
}

Produces same o/p : 100

Vishal yadav said:   1 decade ago
It comes because on the left side of the assignment operator there are more than two variables having ? between the if you use (b=100) instead of it, there will be no error.

Gourav said:   10 years ago
#include<stdio.h>
int main()
{
int a = 4, b=1;
a >=5 ? b=100: 200;
printf("%d\n", b);
return 0;
}

Output is 1 why? It must be 200 right.
(1)

Rishikesh Sonawane said:   4 years ago
1) Ternary operator has high precedence than "=".
2) So the compiler is , taking it as , ((a >=5) ? b=100: b)=200;
Hence the error Lvalue required.

Mani said:   1 decade ago
Hi, You have to assign the value to any variable, but the exp a >=5 ? b=100: 200; is not assigned to any variable. So it gives the error msg of lvalue required.

Vadya said:   1 decade ago
int a = 10, b;
a >=5 ? b=100: 200;
printf("%d\n", b);

This code works.! Why.???
How is it equivalent to b=(a>=5?100:200) ?

Abhishek rai said:   1 decade ago
#include<stdio.h>
int main()
{
int a = 10, b;
a >=5 ? (b=100): (b=200);
printf("%d\n", b);
return 0;
}


Post your comments here:

Your comments will be displayed after verification.