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:
- Check the integer in a conditional statement for a “bad” value, and then use a switch statement to handle the “bad” value(s), or
- 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.
The first test should probably be:
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_codewith the precedingenum; you would have to add:There will be very little difference between the two in terms of generated code.
I would probably use Option 1 (the
ifnotation) 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.