Mark Lepro wrote:Thank you guys for the replies, I really appreciate.
If I understand correctly, my variable "secs" is sort of forgotten (out of scope) when I only initialize it in the loop statement.
No.
If it was out of scope, the error message would have been something like "undefined symbol". When you get "might not be initialized," it means you're doing something like this:
or even this:
In both cases, when we get to the println(), the compiler cannot be sure that x has been given a value. In the second case, even though you and I can say, "But if the first condition doesn't get executed, then the second one has to!" the compiler does not do that kind of analysis. Note that if we change the second "else if" to just "else", then the compiler can be sure that exactly one of the paths will be executed.
This kind of behavior can also occur with loop:
Again, if condition is false when we first hit the for or while, then the body will never be executed, and x will not be set.
Note tat the WRONG way to fix this is to just blindly give the variable an initial value to make the compiler happy. We have to examine our logic to see what path we forgot. In some cases, it turns out that the right solution is to give the variable an initial value, but we only do that after we've closely examined our logic, and only if it makes sense for the variable to actually have that value because we're going to use it.