-10
#include <iostream>
using namespace std;
int main()
{
    if (!(cout << "geeks"))
       cout <<" geeks ";
    else
       cout << "forgeeks ";

    return 0;
}

Why is cout << "geeks"; inside the if condition executed? I know that the if statement is false. I expected "forgeeks " only.

Boann
  • 48,794
  • 16
  • 117
  • 146

2 Answers2

5

Why is cout << "geeks"; inside the if condition executed?

Because otherwise the computer won't know whether it was "true" or "false"?

Given if (foo()), the function foo must be called; this extends to any expression in general, which must be evaluated before their "result" can be known (though note that sub-expressions may be skipped due to short-circuiting).

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

Focus in below statement:

if (!(cout << "geeks"))

Here cout with << operator which is overloaded to print the stream as output i.e "geeks" and then it return this stream to the if statement.

if statement check the condition i.e if(!("geeks")), which if statement see as if(!(true)), results to false condition.

Hence else statement execute to print "forgeeks".

HarshGiri
  • 408
  • 2
  • 12