I'm trying to brush-up my programming skills. Below program's output is 'I'm in else if 1'. I would like to know the reason behind, why the x value is not initialized to 2 instead it is showing 1.
#include <iostream>
using namespace std;
int main()
{
if (false)
{
cout << "I'm in if " << endl;
}
else if (int x=2 && true)
{
cout << "I'm in else if " << x << endl;
}
else
{
int y = x;
cout << y << endl;
}
return 0;
}
According to operator precedence,
if (int x=2 && true)
is parsed as
if (int x = (2 && true))
so x = true
so 1
.