0
int main() 
{ 
   int year;
   cin>>year; 
  
    
        switch (year)  
        { 
        case 1000 ... 1500: 
            cout<<"less than 1501";
            break; 
        case 1502 ... 2500: 
            cout<<"greater than 1501"; 
            break; 
        case 1501:
            cout<<"1501";
        } 
     
    return 0;
    
}  

Is this more efficient or:-

if(year<1501)
{ 
 cout<<"less than 1501";
}

else if(year>1501 && year<2700)
{
 cout<<"greater than 1501 but less than 2700";
}

This is a small example but if the range is very big and the number of cases are also numerous then will the switch case approach or the if-else will be better.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

2 Answers2

3

For starters, case 1000 ... 1500 isn't valid C++ syntax. If you mean you want to list every individual case between 1000 and 1500, let me tell you it is a bad idea. The most important thing about code is its readability and having 500 consecutive cases is very much the opposite of clean code.

Another thing you should also know is that switch and if statements are not equivalent as to what they are compiled into. if and if else are compiled into simple conditional jumps, while switch is often compiled into lookup table, where value of individual cases is used as an offset for table of addresses and based on that your code will do unconditional jump to corresponding section of code. This is not the guarantee behavior and won't be the case if you have random values for cases, but in right condition (e.g. enums) it has potential to be compiled as lookup. The final result is that for good cases you have no branches (except for range check) and your code will execute a little bit faster.

Keep in mind though that modern hardware is super fast and you simply won't notice the difference between switch and if unless it is in your hot path and even then a single cache miss will be more impactful. For that very reason you should always focus on writing code that is easy to understand and makes the most sense. As for compilation, again, it's the "price" you pay once and as such should not concern you at all. My educated guess for compilation time difference between switch and if is that switch would be a tiny bit slower, but you won't notice it anyway.

NRUB
  • 404
  • 4
  • 17
1

More efficient, still readable and using correct C++ syntax could be:

template <typename T> int sgn(T val) {
    return (T(0) < val) - (val < T(0));
}

switch( sgn(year-1501) ) {
    case -1: std::cout << "less"; break;
    case  0: std::cout << "equal"; break;
    case  1: std::cout << "bigger"; break;
}
std::cout << std::endl;

(thanks https://stackoverflow.com/a/4609795 for the sgn() implementation). But for such small function I hardly doubt you will notice any difference in execution time, so I suggest you implement it most readable way for you and then worry for performance if necessary.

Slava
  • 43,454
  • 1
  • 47
  • 90