0

I have a void function that helps me set the time on my arduino clock. I need to use the same function twice - once for the alarm and once for the actual time. The variables I am defining need to equal either alarmHours and alarmMinutes, or hours and minutes. This was my solution:

void setting(int i){
 if(i==0){
  int mi=alarmMinutes;
  int ho=alarmHours;
 }else if(i==1){
  int mi=minutes;
  int ho=hours;
 }
//more code later
}

I got an error saying that ho and mi are undefined. I fixed this like this:

void setting(int i){

 int mi;
 int ho;

 if(i==0){
  mi=alarmMinutes;
  ho=alarmHours;
 }else if(i==1){
  mi=minutes;
  ho=hours;
 }
}

This solved the problem. Why couldn't I use the first option if I passed in a 0 or a 1 to the parameters of the function?

2 Answers 2

4

Declaring a variable inside a block means that they only exist within that block. Once the block is exited, they become inaccessible.

2
  • Before, I thought that only applies to functions. I guess it applies to all blocks of code, including the if statements.
    – shurup
    Commented Jun 17, 2016 at 20:44
  • 1
    Specifically, it applies to the nearest pair of enclosing braces, {}.
    – JRobert
    Commented Jun 17, 2016 at 23:23
2

The problem with doing it how you originally did is that the variables you initialized inside the if statement do not go onto the else statement.

That is why your solution is correct. You need to declare your variables before going inside of a block in order to use them.

There are uses for declaring a variables inside of a block.. but this is not one of them as you realized and fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.