C Programming - Control Instructions - Discussion

Discussion Forum : Control Instructions - Point Out Correct Statements (Q.No. 8)
8.
Which of the following statements are correct about the below program?
#include<stdio.h>
int main()
{
    int n = 0, y = 1;
    y == 1 ? n=0 : n=1;
    if(n)
        printf("Yes\n");
    else
        printf("No\n");
    return 0;
}
Error: Declaration terminated incorrectly
Error: Syntax error
Error: Lvalue required
None of above
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
22 comments Page 2 of 3.

Rohini said:   1 decade ago
Problem : y==1? n=0:n=1;

Soln: There should be variable on a left-side of assignment operator to hold than it will give proper result.

int x;
x=(y==1?n=0:n=1);
where x = 1(true value returned)

Sanjana said:   1 decade ago
What do you mean by ((y==1)?n)=0:n=1;?

Debashish Ghosh said:   1 decade ago
When the compiler reaches the second n in
y == 1 ? n = 0 : n = 1;
It is convinced that the conditional expression is completely scanned. This expression evaluates to an R-value after which the compiler encounters an assignment operator (=). So essentially the compiler sees the above statement as
(y == 1 ? n = 0 : n) = 1;.
And the expression inside the brackets evaluates to an R-value. Since we can not place an R-value before the assignment operator (=), the compiler generates the error message "L-value required".
(1)

Navneeraj Mishra said:   1 decade ago
In turbo c this prog gives error: "L-value required".

While in dev c++ its executes successfully and gives the o/p as: No

Ashok said:   1 decade ago
Thank you kiran.

Ravi said:   1 decade ago
#include<stdio.h>
int main()
{
int n = 0, y = 1;
y == 1 ? n=0 : n=1;
if(n)
printf("Yes\n");
else
printf("No\n");
return 0;
}

Compile and run the following code in Turbo C or in GCC.
The conditional operator ?: has following form.
(condition)?true part : false part.

Thus, the value of n will be 0 not 1.

Manjuanath (mj) said:   1 decade ago
In grouping is required otherwise error as Lvalue required.

y == ? (n=0):(n=1);

Here you will not get error friends.
(1)

Suraj said:   10 years ago
Yes, @Sandya is right when run these code in GCC it also gives "NO" as a output and if you assign n=1 in if than it gives "YES" as a output so before If there is no bug.

Amit said:   8 years ago
The syntax y == 1 ? n=0 : n=1; should be written as y==1?0:1;.

Chethan N said:   8 years ago
Expression? True(1):false(0)
In false condition it's always value is 0.
We don't modify it,

If can't assign the value n=1 in false condition.


Post your comments here:

Your comments will be displayed after verification.