5 years, 2 months ago.

For loops don't work if more than 1 cycle

My for loop will not execute unless it is only one cycle. Code on either side will execute, the programme simply skips over the loop.

This is the full code, it runs perfectly fine:

full code

#include "mbed.h"

// Green LED
DigitalOut led1(LED1);
// Blue LED
DigitalOut led2(LED2);
// Red LED
DigitalOut led3(LED3);


void select_led(int l)
{
        if (l==1) {
                led1 = true;
                led2 = false;
                led3 = false;
        }
        else if (l==2) {
                led1 = false;
                led2 = true;
                led3 = false;
        }
        else if (l==3) {
                led1 = false;
                led2 = false;
                led3 = true;
        }
}



int main() {
    for(int i=2; i==2; i++) {
        select_led(i);
        wait(1);
    }       
}

If I change the for loop to this nothing happens:

bugged code

int main() {
    for(int i=1; i==2; i++) {
        select_led(i);
        wait(1);
    }       
}

1 Answer

5 years, 2 months ago.

Hello Andre,

The condition in for loop is evaluated before each iteration.

In first case when

for(int i=2; i==2; i++)

it evaluates to true

2==2 ? -> true

and the statements in the loop's body are executed.

In second case when

for(int i=1; i==2; i++)

it evaluates to false

1==2 ? -> false

and the loop expires without executing the statements in the loop's body.

Try:

for(int i=1; i<=2; i++) {
    select_led(i);
    wait(1);
}