Matt Harrison
Matt Harrison

Reputation: 13587

Confusing increment behaviour

int i = 1;

void setup() {
  Serial.begin(9600);
}

void loop() {
    if(i == 1){
      Serial.print(i);
    }
    i++;
}

This is intended to only print the value of i once. Why does it keep printing 1 forever?

This code works properly only writing i once:

int i = 1;

void setup() {
  Serial.begin(9600);
}

void loop() {
    if(i == 1){
      Serial.print(i);
    }
    i = 2;
}

Upvotes: 1

Views: 73

Answers (3)

Dennis Johansson
Dennis Johansson

Reputation: 43

If you want your first example to work longer. Change "int" to "long".

int can only store 2 bytes. -32,768 to 32,767. You will reach this number really fast. long can store 4 bytes. -2,147,483,648 to 2,147,483,647. This will take a whiiiile.

Upvotes: 1

ladislas
ladislas

Reputation: 3070

You may also want to add some delay because sometimes you can miss the first Serial.println();.

Something like that:

int i = 1;

void setup() {
  Serial.begin(9600);
  delay(1000); //wait for one second
}

Hope it helps!

Upvotes: 1

alk
alk

Reputation: 70981

Assuming loop() is called in a loop:

  • i will overflow in the first example.

  • In the second example it is fixed to the value of 2 after the first iteration.

Upvotes: 4

Related Questions