Reputation: 13
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:
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.
Upvotes: 0
Views: 173
Reputation: 37837
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.
Upvotes: 1
Reputation: 754610
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.
Upvotes: 1