0

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

  • 1
    Simple put, you can do assignment in conditions with some languages. See this question for an example of such: http://stackoverflow.com/a/18450261/2127492 – jrbeverly Aug 13 '16 at 01:23

1 Answers1

2

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 trueto the variable and the first condition will always be satisfied (as the result of the assignment would be 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...)

assignment (=) operator.
equality (==) operator.

pgenfer
  • 597
  • 3
  • 13