-3
#include <iostream>    
    
int main() {
    std::cout << (2 == 2) && (10 < 5); 
}

This code prints 1 (true), but I expect it to print 0 (false). I have tried to run the same code in several compilers, and they all give the same surprising result.

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
  • 12
    [Operator precedence](https://en.cppreference.com/w/cpp/language/operator_precedence). Your expression is interpreted as `(std::cout << (2 == 2)) && (10 < 5)` – Yksisarvinen Aug 22 '23 at 11:37
  • 3
    More exactly, the expression *returns* 0, because the first operand evaluates to `cout` and the second to false, but the first operand `cout << (2 == 2)` *displays* 1. – Serge Ballesta Aug 22 '23 at 11:45
  • In C/C++ the operator << has a wrong (unintuitive and impractical) precedence order. – Yves Daoust Aug 22 '23 at 11:47
  • @YvesDaoust: It is mostly as `<<` is used for different kind of operation. we would have different expectation of operator precedence between bitshift and streaming, but they both use the same `<<`. – Jarod42 Aug 22 '23 at 12:04
  • @Jarod42: I should have said wrong *in all cases*. – Yves Daoust Aug 22 '23 at 12:05
  • 1
    So it makes sense to be explicit and write `std::cout << ((2 == 2) && (10 < 5));`. Side note stop using `using namespace std;` – Pepijn Kramer Aug 22 '23 at 12:17
  • @StephenNewell "*missing an argument list for main*" - `main()` is allowed to omit its arguments. – Remy Lebeau Aug 22 '23 at 17:15
  • @RemyLebeau - The question was edited since my comment. The original version looked like `int (main) {`. – Stephen Newell Aug 22 '23 at 23:48

0 Answers0