Page 1 of 1

c++ using switch over if?

Posted: Tue Sep 30, 2014 10:43 am
by gregar1000
Can anyone tell me the benefits of using switch over if?
totally confused!

Re: c++ using switch over if?

Posted: Tue Sep 30, 2014 11:15 am
by AdventWolf
I haven't programmed much in a while but I believe If statements allow for much more flexibility. If you use a switch statement I think you can only compare a single variable with one logical operator, but in an if statement you can compare an endless amount of variables with any logical operator. I prefer to use if/else statements because they are just cleaner and allow more functionality I think. Let more knowledgeable coders correct me if I am wrong.

EX:

Code: Select all

int main()
{
    int x = 1;

    switch(x)
    {
    case 1:
        std::cout << "1\n";
        break;

    case 2:
        std::cout << "2\n";
        break;

    case 3:
        std::cout << "3\n";
        break;

    default:
        std::cout << "Unknown\n";
    }
    return 0;
}

Code: Select all

int main()
{
    int x = 1;

    if( x >= 1 && x <= 3 )
        std::cout << "1-3\n";

    else if( x >= 4 && x <= 40 )
        std::cout << "4-40\n";

    else if( x >= 41 && x <= 100 )
        std::cout << "41-100\n";

    else
        std::cout << "Unknown\n";
    }
    return 0;
}

Re: c++ using switch over if?

Posted: Tue Sep 30, 2014 11:17 am
by wololo
switch is faster, it's also much more easier to read in general. You would use "if" only when your condition cannot be represented easily enough with integers at compile time.

Re: c++ using switch over if?

Posted: Tue Sep 30, 2014 11:31 am
by gregar1000
Thanks guys. Just starting out with C++. trying to get the basics down! :)

Re: c++ using switch over if?

Posted: Fri Oct 03, 2014 6:40 pm
by Acid_Snake
wololo wrote:switch is faster
only when the presented integers are in a small enough range to be used as indexes for an array of pointers or in the range of the program's code