Advantage of switch over if-else statement

后端 未结 22 2378
梦谈多话
梦谈多话 2020-11-22 11:08

What\'s the best practice for using a switch statement vs using an if statement for 30 unsigned enumerations where about 10 have an ex

22条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 11:40

    When it comes to compiling the program, I don't know if there is any difference. But as for the program itself and keeping the code as simple as possible, I personally think it depends on what you want to do. if else if else statements have their advantages, which I think are:

    allow you to test a variable against specific ranges you can use functions (Standard Library or Personal) as conditionals.

    (example:

    `int a;
     cout<<"enter value:\n";
     cin>>a;
    
     if( a > 0 && a < 5)
       {
         cout<<"a is between 0, 5\n";
    
       }else if(a > 5 && a < 10)
    
         cout<<"a is between 5,10\n";
    
       }else{
    
           "a is not an integer, or is not in range 0,10\n";
    

    However, If else if else statements can get complicated and messy (despite your best attempts) in a hurry. Switch statements tend to be clearer, cleaner, and easier to read; but can only be used to test against specific values (example:

    `int a;
     cout<<"enter value:\n";
     cin>>a;
    
     switch(a)
     {
        case 0:
        case 1:
        case 2: 
        case 3:
        case 4:
        case 5:
            cout<<"a is between 0,5 and equals: "<

    I prefer if - else if - else statements, but it really is up to you. If you want to use functions as the conditions, or you want to test something against a range, array, or vector and/or you don't mind dealing with the complicated nesting, I would recommend using If else if else blocks. If you want to test against single values or you want a clean and easy to read block, I would recommend you use switch() case blocks.

提交回复
热议问题