c++ - Advantage of switch over if-else statement -


what's best practice using switch statement vs using if statement 30 unsigned enumerations 10 have expected action (that presently same action). performance , space need considered not critical. i've abstracted snippet don't hate me naming conventions.

switch statement:

// numerror error enumeration type, 0 being non-error case // fire_special_event() stub method shared processing  switch (numerror) {     case error_01 :  // intentional fall-through   case error_07 :  // intentional fall-through   case error_0a :  // intentional fall-through   case error_10 :  // intentional fall-through   case error_15 :  // intentional fall-through   case error_16 :  // intentional fall-through   case error_20 :   {      fire_special_event();   }   break;    default:   {     // error codes require no additional action   }   break;        } 

if statement:

if ((error_01 == numerror)  ||     (error_07 == numerror)  ||     (error_0a == numerror)  ||      (error_10 == numerror)  ||     (error_15 == numerror)  ||     (error_16 == numerror)  ||     (error_20 == numerror)) {   fire_special_event(); } 

use switch.

in worst case compiler generate same code if-else chain, don't lose anything. if in doubt put common cases first switch statement.

in best case optimizer may find better way generate code. common things compiler build binary decision tree (saves compares , jumps in average case) or build jump-table (works without compares @ all).


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -