简体   繁体   English

解释这个例子中的变量声明和输出

[英]Explain variable declaration and output in this example

I'm confused at this example:我对这个例子感到困惑:

int x = 5;
if (x==5) cout << x; // output 5
if (x==6) cout << x;
if (x=6) cout << x; // output 6
x = 0;
if (x=0) cout << x;
x = 5;
if (x-5) cout << x;
if (x-6) cout << x; // output 5

I understand first if (x==5) , but why does it output 6 at if (x=6) when x = 5, and why won't it output 0 in if(x=0)我首先理解if (x==5) ,但是为什么当 x = 5 时它在if (x=6)处输出 6,为什么它在if(x=0)不输出 0

if (x=6)

means not comparison, but assignment.不是比较,而是赋值。 You assign 6 to x and the return value of the expression is 6, which is not 0 so it gains true.您将 6 分配给 x 并且表达式的返回值是 6,它不是 0,因此它为真。

similar with if (x=0) The expression x=0 gains 0 so it means if(0)类似于if (x=0)表达式 x=0 得到 0 所以这意味着if(0)

The thing about computers is that they're extraordinarily literal.关于计算机的事情是它们非常直接。 A missing semicolon, or an added character, can completely change a program's function.缺少的分号或添加的字符可以完全改变程序的功能。 So you need to be just as careful as a computer when working wth programs.因此,在处理程序时,您需要像计算机一样小心。

As @juanchopanza alluded to, there is a difference between == and = - and you already know what it is.正如@juanchopanza 所暗示的, === - 之间存在差异,而您已经知道它是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM