1 2 3
|
for (int i = newDay; i > monthMax[month-1]; ++month) {
if (month > 12)
month = 1;
|
You have to understand the order in which this code is run. For loops work like this:
1) Run initialization (
int i = newDay;
)
2) Check condition (
i > monthMax
). If false, exit loop. If true, continue to step 3
3) Run loop body
4) Do the increment (
++month
)
5) Go to step #2
Notice how i > monthMax is checked
immediately after you increment month. You don't wrap month to 1 until the loop body, which happens
after the condition is checked. Which means the condition is checked with 'month' being 13, which is very bad because you're stepping out of bounds of your array.
Really, this loop is poorly formed. The initialization and condition are focused on 'i' being the variable that drives the loop.. but the increment modifies 'month' instead of 'i' so it's very weird.
For loops are typically used when you want to run a X times -- and X is typically known. Here you don't really know what X is, so a for loop isn't really suitable.
I would rewrite this with a while loop.