Error with io stream

What's the problem with the last two operations in the code?

#include <iostream>
using namespace std;
int main()
{
cout << "2 + 4 = " << 2 + 4 << endl;
cout << "2 * 4 = " << 2 * 4 << endl;
cout << "2 | 4 = " << 2 | 4 << endl;
cout << "2 & 4 = " << 2 & 4 << endl;

      

What should I do to fix this?

+2


source to share


2 answers


What's the problem with the last two operations in the code?

Operator priority. |

and &

are of lower precedence than <<

, therefore, cout << "2 & 4 = " << 2 & 4 << endl;

parsed as (cout << "2 & 4 = " << 2) & (4 << endl;)

.



What should I do to fix this?

Place parsers around 2 | 4

and 2 & 4

.

+9


source


Place the expression in parentheses. The operator <<

takes precedence over the bitwise operators.



#include <iostream>
using namespace std;
int main()
{
  cout << "2 + 4 = " << 2 + 4 << endl;
  cout << "2 * 4 = " << 2 * 4 << endl;
  cout << "2 | 4 = " << (2 | 4) << endl;
  cout << "2 & 4 = " << (2 & 4) << endl;
  return 0;
}

      

+3


source







All Articles