Reputation: 11
This may be the worst way of doing this but I want the Arduino to pick between 1 and -1. This code is not working, what is wrong.
This is my understanding of the code:
The int is defined as 0.
The while loop starts because the condition is true.
A random variable is chosen.
If the int is 1 or -1 then the while loop ends and the value is printed.
If the int is 0 the while loop restarts.
int random_number = 0;
void setup() {
Serial.begin(9600);
while (random_number == 0){
int random_number = random(-1,2);
Serial.println(random_number);
delay(1000);
}
Serial.print("value ");
Serial.println(random_number);
}
void loop() {
}
Upvotes: 0
Views: 226
Reputation: 1
To provide a little clarity to eventHandler's (correct) response, since there appears to still be confusion for someone reading it:
The problem lies in the line
int random_number = random(-1,2);
because by including a type specifier (the int
declarator), a new variable called random_number
is being declared within the scope of the while
loop. This variable, as pointed out before, is not the same as the one declared globally in the line
int random_number = 0;
thus it is not the one being used in the while
loop condition.
Generally, multiple declaration is flagged by the compiler as being an issue, but since the variables in the question have different scopes, what is actually being done is called shadowing. Here, the random_number
of the loop is hiding (or shadowing) the one declared in the global scope and so it is being assigned a random number instead of the intended variable. When variables with different scopes are being resolved, the "most local" one is given preference over the "least local" one.
The definition of random_number
in the while
loop should thus read:
random_number = random(-1,2);
in which case the global variable is being assigned a new value (instead of a new variable being assigned one), only one variable of that name exists in the code snippet, and the issue is resolved.
Upvotes: 0
Reputation: 1211
The problem is that you are declaring random_number
inside the while loop again. This is a new and different variable in the local scope of the loop, not the one declared globaly at the begining of your code. Also, it is being declared again on every loop.
int random_number = 0;
void setup() {
Serial.begin(9600);
while (random_number == 0){
random_number = random(-1,2); // not declared again
Serial.println(random_number);
delay(1000);
}
Serial.print("value ");
Serial.println(random_number);
}
void loop() {
}
Note that int random_number
is replaced by random_number
inside the loop. Now the globally declared variable random_number
is being used instead of declaring a new local variable with the same name.
Upvotes: 3