Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:
Serial.begin(9600);
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  delay(1500); 
  carrier.begin();
  carrier.display.setRotation(0);
  a =1;


}

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

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

strange counting

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading