Why is my variable jumping in value when I add an "if" condition?


The code below, without the if statement, count’s up from 1 to infinite and shows this in the console as intended.
If I add the if statement, I get what’s shown in the screenshot below. Why does this happen?

#include <Arduino_MKRIoTCarrier.h>
MKRIoTCarrier carrier;
int a;
int r,g,b;

void setup() {
  // put your setup code here, to run once:
  // Initialize serial and wait for port to open:
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  a =1;


void loop() 
  // put your main code here, to run repeatedly:
  a =a + 1;

if (a = 10)
      carrier.leds.setPixelColor(0, 255, 0, 0);

>Solution :

In c++, comparison is ==, so you need to write if (a == 10). When you write, a = 10, that’s an assignment: a will have the value of 10 and the evaluation value is also 10 (to be precise, reference to a which is 10), thus in if() it evaluates to true.

Leave a ReplyCancel reply