[英]OOP static variable changing value
I recently came upon this code in a comic, which I did not understand. 我最近在漫画中遇到了这个代码,但我不理解。 Can someone please explain this to me?
有人可以向我解释一下吗? Is there any reason why the variable should change it's value?
有什么理由为什么变量应该更改其值?
static bool isCrazyMurderingRobot = false;
void interact_with_humans(void) {
if (isCrazyMurderingRobot = true)
kill(humans);
else
be_nice_to(humans)
}
Here is the comic: http://oppressive-silence.com/comics/oh-no-the-robots 这是漫画: http : //oppressive-silence.com/comics/oh-no-the-robots
The reason might be that in many programming languages, checking for equality is done by using ==
, while using a single =
sign would assign the value to the variable). 原因可能是在许多编程语言中,通过使用
==
来检查是否相等,而使用单个=
符号会将值分配给变量。
So the code 所以代码
if (isCrazyMurderingRobot = true)
would assign true
to the variable and the first condition will always be satisfied (as the result of the assignment would be true). 会将
true
赋给变量,并且始终满足第一个条件(因为赋值的结果为true)。
The correct line would be: 正确的行是:
// use '==' here instead of '=' to check if variable is set
// using a single '=' would assign the value instead
if (isCrazyMurderingRobot == true)
For more details, please check these descriptions (they are for the C# language, but the operators behave similar in other languages like Java etc...) 有关更多详细信息,请检查这些描述(它们适用于C#语言,但运算符在其他语言(如Java等)中的行为类似。)
assignment (=) operator. 赋值(=)运算符。
equality (==) operator. 等于(==)运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.