Why does this code work just like the other more 'proper' style of code?

Device: Arduino UNO
Program: Arduino
Case: Turning on multiple LEDs on a breadboard using a function + array, but I am told that my style isn't consistent and improper, and I want to know if it's just dumb luck or if it's consistent and could be used whenever necessary.
IMPORTANT NOTE: Both sets of code work the exact same way.

My Style (Improper use of array):
/////////////////////////////////////////////
int led[] = {13, 12, 11}; //Array for LEDs
int t = 500; //Set time delay as 1 second

void setup() { //Led = OUTPUT device
int i;
pinMode (led[i], OUTPUT);
}

void Light (int i, int br, int i2, int br2) { //Function for led lights
digitalWrite (led[i], br);
digitalWrite (led[i2], br2);
delay (t);
}

void loop() { //Task main
Light (0, HIGH, 1, LOW);
Light (0, LOW, 1, HIGH);
Light (1, LOW, 2, HIGH);
Light (0, LOW, 2, LOW);
}
//////////////////////////////////////////////

Proper use of array:
/////////////////////////////////////////////
int led[] = {13, 12, 11};

void setup()
{
for(int i=0;i<3;i++)
{
pinMode(led[i], OUTPUT);
}
}

void loop()
{
for(int i=0;i<3;i++)
{
digitalWrite(led[i], HIGH);
delay(1000);
digitalWrite(led[i], LOW);
delay(1000);
}
}
////////////////////////////////////////////
Last edited on
1) When posting code, please use code tags to make it readable:

http://www.cplusplus.com/articles/z13hAqkS/

2) What exactly is it that you think shouldn't work? The call to pinMode()? Without seeing what that function actually does, we can't really say.

We cannot read minds. Give us the information we need to actually answer your question.

3) Undefined behaviour is undefined behaviour. Sometimes that can mean that, by chance or design, the values that end up memory are the same as the ones that would go in there if you'd written your code correctly. Which, really, is the worst-case scenario, because it means you often don't become aware of the bug until some unusual circumstance causes it to screw things up in the field.

The best kind of bug is the one that you can see straight away.

Last edited on
In the setup() function you have not given a value to variable i so you can't be sure what value it will have, or if it's a valid index to use in the array.
Topic archived. No new replies allowed.