Home > Software design >  Why is "sizeof(unsigned int) == sizeof(int)" refused in a cout?
Why is "sizeof(unsigned int) == sizeof(int)" refused in a cout?

Time:09-27

Why can I write:

bool a = sizeof(unsigned int) == sizeof(int);
cout << "(taille unsigned integer = integer) ? " << a;

But this:

cout << "(taille unsigned integer = integer) ? " << sizeof(unsigned int) == sizeof(int);

produces a compilation error?

Invalid operands to binary expression ('std::basic_ostream<char>::__ostream_type' (aka 'basic_ostream<char, std::char_traits<char>>') and 'unsigned long')

CodePudding user response:

This is an issue of operator precedence. The << operator has higher prcedence than ==, so your expression is parsed as

(cout << "(taille unsigned integer = integer) ? " << sizeof(unsigned int)) == (sizeof(int))

Since the ostream << operator overloads return the ostream they're called on, you're trying to compare a std::ostream to an int, and there is no such comparison.

CodePudding user response:

Due to operator precedence, add parentheses around ==.

Without them, it is interpreted as:

(cout << "? " << sizeof(unsigned int) ) == sizeof(int);
  •  Tags:  
  • c
  • Related