What is the output of C++ program given below?
#include<iostream>
using namespace std;
int main()
{
int y=8,x=6;
(x=5)&&(x=7) ? y=1:y=2;
cout<<x<<"_"<<y;
}
Note: _ (underscore is used in cout statement to differentiate x & y value.
-
1_7
-
7_1
-
5_1
-
6_2
-
None of the above
B
Correct answer
Explanation
Though variables x,y are intialized with 6, 8 respectively.
Due to below statement the values of x,y are changed.
(x=5)&&(x=7) ? y=1:y=2;
Conditional operator (?:) follows right to left associativity.
&& operator follows left to right associativity.
= opeartor always returns true.
Evaluate the condition (x=5)&&(x=7) first.
proceed left to right due to &&
Hence x=7 finally, and condition returns true because (true&&true implies true)
Hence y=1;
Which prints 7_1