aherlambang
aherlambang

Reputation: 14418

error with io stream

What is the problem with the last two statements 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?

Upvotes: 2

Views: 100

Answers (2)

sepp2k
sepp2k

Reputation: 370122

What is the problem with the last two statements in the code?

Operator precedence. | and & have lower precedence than <<, so cout << "2 & 4 = " << 2 & 4 << endl; gets parsed as (cout << "2 & 4 = " << 2) & (4 << endl;).

What should I do to fix this?

Put parens around 2 | 4 and 2 & 4.

Upvotes: 9

Brian R. Bondy
Brian R. Bondy

Reputation: 347216

Put the expression in parentheses. The << operator is taking 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;
}

Upvotes: 3

Related Questions