views:

42

answers:

2

Hello all.

I'm not very familiar with machine code, but I think this is a pretty simple question.
If I want to do error handling via an integer returned from a function (as opposed to the function throwing an exception), is it better practice—from a machine code standpoint—to:

  1. Check the integer in a conditional statement for a "bad" value, and then use a switch statement to handle the "bad" value(s), or
  2. Switch the integer, and provide a case for the "good" value(s) as well as the "bad" value(s)

For example, in C++:

enum error_code {E_GOOD, E_BAD, E_UGLY};
error_code func_b();

Option 1

void func_a()
{
    error_code err_catch = func_b();

    if (err_catch)
    {
        switch (err_catch)
        {
        case E_BAD:
            /* Handle bad case */
            break;
        case E_UGLY:
            /* Handle ugly case */
            break;
        }
    }
}

Option 2

void func_a()
{
    error_code err_catch = func_b();

    switch (err_catch)
    {
    case E_GOOD:
        break;
    case E_BAD:
        /* Handle bad case */
        break;
    case E_UGLY:
        /* Handle ugly case */
        break;
    }
}

Thank you for your help.

+1  A: 

The first test should probably be:

if (err_catch != E_GOOD)

It is explicit about 'an error occurred'. Incidentally, your code looks like is passing through a C++ compiler. C does not create a type error_code with the preceding enum; you would have to add:

 typedef enum error_code error_code;

There will be very little difference between the two in terms of generated code.

I would probably use Option 1 (the if notation) simply to make it clear that the switch only deals with error cases (because it only has to deal with error cases), but I wouldn't object to either if it was presented to me for code review.

Jonathan Leffler
Ah yes, forgot C doesn't do automatic `typedef` s. Minor change to C++.
cordella
+1  A: 

With enum types, I would directly use a switch statement so that the compiler can make sure the switch statement really handles all possible values.

ndim
Now that you mention that, I do remember the compiler complaining about not using one of the `enum` values in a `switch` that checked it, and oddly enough it was the `E_GOOD` value. This was in a `catch` block, so I had no reason to provide an `E_GOOD` case, but the compiler still warned about it.
cordella