Learned something new last week looking over a programming contest test. Turns out that
default doesn’t have to be the last condition in a
switch case statement. At least, not in Java.
I knew you could leave it off. But everywhere I’ve ever seen a
switch case statement that included
default was the last condition.
Going off of memory, this is pretty close to the problem from the test. It asked for output, and “No output, error” was an option.
If you run this it’ll print out
3 even though the
default comes before it. If you change
x to something other than 2, 3 or 4 it’ll print out
switch statement I’ve ever written has
default at the end. Now though I’m wondering if it makes more sense for it to come first.
That seems a little more readable to me, but I think the fact that
default isn’t where everyone would expect it to be makes it worse. I’d never put it in the middle though. That’s just painful.
Either way, it was an interesting problem and lead to a good discussion in class. Pretty much everyone, including me, missed the problem.
Want to stay in touch and keep up to date with the latest posts @ CompSci.rocks?