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?
source to share
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
.
source to share
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;
}
source to share