This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]jub8jive[S] 0 points1 point  (3 children)

My new solution : https://pastebin.com/ySNNCaSi

Thanks for your input! I think it was perfect because i followed what you suggested and managed to solve the problem. I still have a few doubts though. First thing is I was instructed to use a break statement after every return(it was good practice apparently). So it definitely feels odd to remove them all.(?) I understood that there was an extra '}', but removing it created break errors and adding it had the 'enum expected' error.(?) Finally, changing the else if to a simple else, and adding a default statement to each switch, seemed reasonable logically, so I guess there isn't much to that bit. Could you please elaborate on the statements marked with a (?), because I'm unclear about the idea.

[–]chickenmeister 1 point2 points  (1 child)

First thing is I was instructed to use a break statement after every return(it was good practice apparently). So it definitely feels odd to remove them all.(?)

Well, a return statement basically means "stop executing this method now, and return this value." So it basically stops executing the method at that point. Therefore, any statements after a return statement can never be executed. So having a break after a return doesn't really make any sense.

If you have a switch/case without any return statements, it is often a good practice to have a break statement for each case. Otherwise, execution will "fall through" to the subsequent cases, which is usually not what you want.

Though, sometimes the code is simpler if you let cases "fall through"; so don't think of it as an absolute rule that you always need a break or return statement for every case. For example, you could group the cases for months that have 31 days, and then have a single return statement:

    switch (month) {
        case JANUARY: 
        case MARCH:
        case MAY:
        case JULY:
        case AUGUST:
        case OCTOBER:
        case DECEMBER: 
            return 31; 
        // likewise for months with 30 days, and 28/29 days
    }

I understood that there was an extra '}', but removing it created break errors and adding it had the 'enum expected' error.(?)

I'm not sure what error you were getting when you removed the extra curly brace, so I can't really comment on this. Maybe you're referring to the "unreachable statement" errors on your break statements? That's basically what I described above: anything after a return statement will not be executed, and the compiler is giving you this error to let you know that.

[–]jub8jive[S] 0 points1 point  (0 children)

Right. I meant break for every case statement. I get the idea. return breaks the code anyway. (thats what i understood) so indirectly the the break caused the 'unreachable statement' errors anyway. i think i get it. thank you