switch case vs if else

if we compare this codes.....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<stdio.h>

int main()
{
    int x;
    printf("enter a number under 3 : ");
    scanf("%d",&x);

    if(x==1)
        printf("it's 1");
    else if(x==2)
        printf("it's 2");
    else if(x==3)
        printf("it's 3");
    else
        printf("i am useless program i don't do anything else");

    return 0;

}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<stdio.h>

int main()
{
    int x;
    printf("enter a number under 3 : ");
    scanf("%d",&x);

    switch(x)
    {
    case 1:
        printf("it's 1");
        break;

    case 2:
        printf("it's 2");
        break;

    case 3:
        printf("it's 3");
        break;

    default:
        printf("i am useless program i don't do anything else");
    }
    return 0;

}


are there any difference in case of CPU usage and performance.


closed account (zb0S216C)
Since switch can only handle integral types, the compiler will be able to construct a jump table and will be able to optimise the labels. Since there's next to no prediction in a jump table, there's virtually zero chance of a false branch prediction.

As for ifs, they can handle all types, which makes it harder for the compiler to optimise. Also, there's a possibility of a false branch prediction, which can affect performance. Though, this is not always an issue. You should note that the compiler limits the number of if nests.

The only way you're going to know for sure is by profiling your program and compare the results.

Wazzak
Last edited on
Only generated by the compiler assembler code can give you correct answer.:)
I must also add:

Switch case statements can only be used to handle 1 type of variable, and crosscheck it's value to that of a non-variable. This is helpfule if that variable has pre-defined values assigned to it, but if there are multiple conditions which must be met, it is better to use an if,then,else. for example:

we want to print the time as am/pm, but we can only retrieve the raw time in military format (24 hours instead of 12.). Here is a little piece from my reminders program which can not possibly be written with a switch case:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
            cout<< "AM/PM:  ";
            while(ampm == "")
            {
                getline(cin, ampm);
            }
            if((ampm == "pm") || (ampm == "PM"))
            {
                if(hour != 12)
                {
                    hour = (hour + 12);
                    while(hour > 24)
                    {
                        hour = (hour - 12);
                    }
                }
            }
            if(((ampm == "am") || (ampm == "AM")) && (hour == 12))
            {
                hour = (hour + 12);
            }
            while(hour > 24)
            {
                hour = (hour - 12);
            }
            if((minute > 59) || (minute < 0))
            {
                minute = 0;
            }


this was used to convert regular time into military time (which is returned when you get the system time) when the user inputs a reminder's time. We have to take the time he/she wants us to remind them, and convert it to military time.
there is more than 1 condition which (has to/can be) met before something is true, or false. If i type in am, and the hour is not 12, it is less than 24. but if i type in am, and the hour is exactly 12, then the hour is now 24. A switch case statement cannot be used here because: 1. some of the data is not an integer and 2. we HAVE to have 'and' and 'or' statements to allow for an accurate parse.

the "possibility of a false branch prediction" can be fixed with a little bit of modifications (trust me, when ur program screws up for no reason, you'll know what it is now) to the if/then statements.

This algorithm has worked perfectly for it's purpose, and my "Reminder" program has always reminded me at the times i set it (no later/earlier). So, yes, "possibility of a false branch prediction" is something to take into account, but keep in mind that sometimes, it is just better to use an if,then,else.
closed account (zb0S216C)
IWishIKnew wrote:
"the "possibility of a false branch prediction" can be fixed with a little bit of modifications (...) to the if/then statements."

And those "modifications" are?

IWishIKnew wrote:
"but keep in mind that sometimes, it is just better to use an if,then,else."

Most of the time, you have no choice but to use if, else if.

Wazzak
You actually don't need any if/else/switch to get a time. One of my earliest "fun" programs:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
	time_t seconds = time (NULL);
	time_t minutes = (seconds % 3600) / 60;
	time_t hours = (seconds / 3600) % 24;  // hours is GMT, I live in Boston
	seconds %= 60;

	// Convert to EST
	hours += ((static_cast<int>(((hours/100.0)- 1.03)*(-1))) - 4 );

	// Make 'A' or 'P'
	char morning = 'A' + ((hours/12)* ('P' - 'A'));

	// Take care of values greater than 12
	hours -= ((hours/13) * 12);

	// Make a 0 a 12
	hours += 12;
	hours -= (( hours / 13 ) * 12);

	// We could do more to make it prettier
	cout << "The local system time (EST) is: "
            << hours  << ":" << minutes << ":" << seconds << " " << morning << "M"<< endl;

	cin.get();
	return 0;
}


Takes advantage of integer division.
Last edited on
Thanks everyone for helping.
Topic archived. No new replies allowed.