C Programming - Control Instructions - Discussion

Discussion Forum : Control Instructions - Find Output of Program (Q.No. 20)
20.
What will be the output of the program?
#include<stdio.h>
int main()
{
    int x, y, z;
    x=y=z=1;
    z = ++x || ++y && ++z;
    printf("x=%d, y=%d, z=%d\n", x, y, z);
    return 0;
}
x=2, y=1, z=1
x=2, y=2, z=1
x=2, y=2, z=2
x=1, y=2, z=1
Answer: Option
Explanation:

Step 1: x=y=z=1; here the variables x ,y, z are initialized to value '1'.

Step 2: z = ++x || ++y && ++z; becomes z = ( (++x) || (++y && ++z) ). Here ++x becomes 2. So there is no need to check the other side because ||(Logical OR) condition is satisfied.(z = (2 || ++y && ++z)). There is no need to process ++y && ++z. Hence it returns '1'. So the value of variable z is '1'

Step 3: printf("x=%d, y=%d, z=%d\n", x, y, z); It prints "x=2, y=1, z=1". here x is increemented in previous step. y and z are not increemented.

Discussion:
19 comments Page 2 of 2.

Pras said:   1 decade ago
This is compiler Dependant, between two sequence point the z is getting modified twice. Thus the output is unpredictable.

Mohammed Rafeeq said:   7 years ago
But ++ operator has higher precedence over logical && so why x, y, z are incremented first?
(1)

Anil said:   1 decade ago
As && operator has higher precedence than || operator,

Why it is not evaluated first?

Lakshmi said:   1 decade ago
How to use && and ||? What is the result of bitwise operators? Please tell me.

Nagaganesh said:   1 decade ago
How ++x become 2?

How should you assign ++x value to z?

How is ++x value true?

Manju said:   1 decade ago
Why we can't take it as ((++x || ++y) && (++z) ) ?

Reema said:   9 years ago
&& should be executed first right?

Shubham Saha said:   7 years ago
Thanks for the explanation @Arindam Paul.

Rashmi said:   1 decade ago
y is also increment.. y will be 2..


Post your comments here:

Your comments will be displayed after verification.