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?

asked Jun 17, 2016 at 18:33

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.

answered Jun 17, 2016 at 18:37
2
  • Before, I thought that only applies to functions. I guess it applies to all blocks of code, including the if statements. Commented Jun 17, 2016 at 20:44
  • 1
    Specifically, it applies to the nearest pair of enclosing braces, {}. 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.

answered Jun 17, 2016 at 19:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.