Advertising (This ad goes away for registered users. You can Login or Register)

c++ using switch over if?

Programming on your favorite platform, for your favorite platform? Post here
Locked
gregar1000
Posts: 21
Joined: Wed Jan 01, 2014 6:47 pm

c++ using switch over if?

Post by gregar1000 »

Can anyone tell me the benefits of using switch over if?
totally confused!
Advertising
AdventWolf
Posts: 6
Joined: Wed Aug 13, 2014 6:18 am

Re: c++ using switch over if?

Post 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;
}
Advertising
wololo
Site Admin
Posts: 3621
Joined: Wed Oct 15, 2008 12:42 am
Location: Japan

Re: c++ using switch over if?

Post 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.
If you need US PSN Codes, this technique is what I recommend.

Looking for guest bloggers and news hunters here at wololo.net, PM me!
gregar1000
Posts: 21
Joined: Wed Jan 01, 2014 6:47 pm

Re: c++ using switch over if?

Post by gregar1000 »

Thanks guys. Just starting out with C++. trying to get the basics down! :)
Acid_Snake
Retired Mod
Posts: 3100
Joined: Tue May 01, 2012 11:32 am
Location: Behind you!

Re: c++ using switch over if?

Post 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
Locked

Return to “Programming”