The following code is working fine in C but when I try to write it in c++ then the program does not work.Please explain.
C code :
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a = 33,b = 7;
printf("%d\n",a&b);
return 0;
}
C++ code:
#include<iostream>
using namespace std;
int main()
{
int a = 33,b = 7;
cout << 33&7 << endl;
return 0;
}
Watch your operator precedence:
cout << (33 & 7) << endl;
&
has lower precedence than <<
. So you need to use ()
.
For the full list of operator precedence in C and C++:
http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
This question nothing has nothing to do with the difference between C and C++. This is about the precedence of the operators and deciding where the borders of the expression are. The right example should look like:
printf("%d\n", a&b);
and
short cout;
int endl;
long var = cout << 33 & 7 << endl;
The fact, that C++ I/O advises to use <<
for printing variables is not important. C++ says that the precedence of the overloaded ops is the same as the precedence of regular operators.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With