Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to put in a default label of a switch?

Let's say I have an enumeration.

enum class ShapeName : char {TRIANGLE,CIRCLE,SQUARE};

and later I have a function like this:

void Function (ShapeName const shape){

    switch (shape){
        case ShapeName::TRIANGLE:
            DoSomething1();
            break;

        case ShapeName::CIRCLE:
            DoSomething2();
            break;

        case ShapeName::SQUARE: 
            DoSomething3();
            break;

        default:
            //THIS CODE BLOCK SHOULD NEVER BE EXECUTED!
    }

    return;
}

Although the default label should never be executed, I want to account for the potential bugs that may arise if a programmer adds another value to 'ShapeName' and it's not accounted for in the switch.
What would you recommended I do?

1. Assertions
I could use an assertion, but what am I asserting?

assert(false); //?

2. Exceptions
I could throw an exception, but I don't think that would be very good practice. I'm under the impression that exceptions are for run time events that can not be predicted because of certain environments.

3. Exits
I can just exit the program immediately with an error. That feels like the best idea, but I'm unsure if it's good practice. I thought the advantage of assertions was that you could turn them all off when you were ready ship the program. Then, all that assertion code would no longer exist.


Maybe there is another way that I'm not aware of. I do use a compiler flag that warns about unaccounted for values, but I still want to know what others recommend.

like image 818
Trevor Hickey Avatar asked Apr 28 '12 02:04

Trevor Hickey


1 Answers

I like the idea of asserting with an informative message. Try this:

assert (!"The default case of so-so switch was reached.");

This always returns false, but provides a message you can use.

Edit:
I found the source I pulled this notion out of my memory from; it's in the following book:
C++ Coding Standards - 101 Rules and Guidelines

like image 124
chris Avatar answered Oct 13 '22 08:10

chris