[英]Code working in c but not in c++
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中正常工作,但是当我尝试用c ++编写它时,程序不起作用。请解释。
C code : C代码:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a = 33,b = 7;
printf("%d\n",a&b);
return 0;
}
C++ code: C ++代码:
#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++: 有关C和C ++中运算符优先级的完整列表:
http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence 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++. 这个问题与C和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 ++ I / O建议使用
<<
来打印变量并不重要。 C++ says that the precedence of the overloaded ops is the same as the precedence of regular operators. C ++表示重载ops的优先级与常规运算符的优先级相同。
Your lines will be explained to: 您的行将解释为:
(cout <<33)&(7<<endl);
It should be: 它应该是:
cout << (33&7) << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.