473,406 Members | 2,713 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Switch Case or If Else If

Does either pose any particular benefit and is there a major difference between them?
May 4 '07 #1
8 16449
gpraghuram
1,275 Expert 1GB
Hi,
Switch case is faster compared to if-else if.
Thats what i know abt it.
Thanks
Raghuram
May 4 '07 #2
teesha
4
that depends of the number of your test case.
in my opinion, there's no difference if you have 2 or 3 test conditions but over it "switch case" is faster than " if-else-if ".
May 4 '07 #3
AdrianH
1,251 Expert 1GB
switch is problematic when used badly in terms of maintainability, and can cause inadvertent errors:

Expand|Select|Wrap|Line Numbers
  1. switch(i) {
  2.   case 1:
  3.     // do stuff
  4.   case 2:
  5.     // do other stuff
  6.     break;
  7. }
In the previous example, the programmer may have not intended to cause case 2 to be executed in both cases. i.e. case 1 will 'do stuff' and 'do other stuff' before leaving the switch. Or the programmer may have done it intentionally. It is hard to say. Commenting is best in this situation if it was intentional.

However, switch can be very fast and be maintainable if used appropriately. Depending on the compiler and the sparseness of the cases, it may be an O(1) operation to determine which case is to be executed, where an if would be an O(n) operation where n is the number of if/else if's there are.

When you use one over the other is entirely up to you, but you should balance maintainability and speed as needed when you make your decision.


Adrian
May 4 '07 #4
Does either pose any particular benefit and is there a major difference between them?

Hi,

I think in switch case only char & int values are allowed but in if else you can also compare real numbers.

Regards,

Pravin
May 8 '07 #5
AdrianH
1,251 Expert 1GB
Hi,

I think in switch case only char & int values are allowed but in if else you can also compare real numbers.

Regards,

Pravin
You are partially right. Only integral values are allowed. This includes all signed and unsigned of char, int, long, and long long.


Adrian
May 8 '07 #6
JosAH
11,448 Expert 8TB
A switch clause is just an integer or anything that can be widened to an int
(such as char, short). The GNU compiler (as an example) recognized three
different ways to compile a switch statement, depending on the case values:

1) perfect
2) dense
3) normal

A perfect switch statement has consecutive case values (in no particular order):
Expand|Select|Wrap|Line Numbers
  1. switch (value) {
  2.    case 3: do3(); break;
  3.    case 5: do5(); break;
  4.    case 4: do4(); break;
  5. }
Code generated for this switch statement involves a simple jump table:
0: address of do3();
1: address of do4();
2: address of do5();
the address to be jumped to is table[value-3].

A dense switch statement is like a perfect switch table where all the case
clauses are almost consecutive and the resulting jump table would be dense.
The empty entries point to the address where the (optional or empty) default
case selector is located.

A normal switch statement also uses a jump table and a case value table which
again is sorted. The value table is consulted using a binary search for the case
selector value. If the entry is found, the jump table destination is used,
otherwise the default case clause address will be used.

The first to variants are O(1) while the third variant is O(log(n)) where n is the
number of case clauses in the switch statement. The AIX xlc compiler suite
attempts to find a perfect hash function for a normal switch statement which
can result in O(1) behaviour even for normal (sparse) switch statements. This
attempt can fail and code similar to GNU's compiler generated code for the
normal switch statement is generated.

kind regards,

Jos
May 8 '07 #7
The "if" statement allows multiple conditions while in switch case we use it only when we have ti check for equality.

Another reason beween them is that "if" condition allows floating points whereas switch condition doesn't allows floating points.
Oct 22 '10 #8
donbock
2,426 Expert 2GB
In a switch statement you only specify the name of the variable once; in an if-else-if cascade you specify the variable for each leg. Thus, the if-else-if cascade offers you more opportunity to misspell the variable.

It is easier for a maintenance programmer to see that each case refers to the same switch variable than it is to see that each leg of an if-else-if cascade refers to the same variable.

Some static analyzer tools (such as Flexelint) will warn you if the switch variable is an enumerated type and you don't have a case statement for every enumeration constant.

It is generally more important for your code to be easy for a human to understand than it is for the code to be optimized for size or speed.
Oct 23 '10 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

15
by: Mike and Jo | last post by:
I've been converting some code to C++. I'm trying to use the Switch function to compare a result. Is it possible to use switch to evaluate '>0', '<0', 0? Example switch (result) { case...
6
by: Aristotelis E. Charalampakis | last post by:
Hi all, this is a newbie question :-) I was wondering if there was a way to use the switch statement in a manner that each case statement includes more that a simple value. i.e.: switch (...
10
by: clueless_google | last post by:
hello. i've been beating my head against a wall over this for too long. setting the variables 'z' or 'y' to differing numbers, the following 'if/else' code snippet works fine; however, the ...
11
by: hasadh | last post by:
Hi, is the assemly code for if..else and switch statements similar. I would like to know if switch also uses value comparison for each case internally or does it jump to the case directly at...
18
by: swaroophr | last post by:
Which of switch statement and if-else statement takes less time to execute?
10
by: Evie | last post by:
I understand that when a switch statement is used without breaks, the code continues executing even after a matching case is found. Why, though, are subsequent cases not evaluated? I wrote a...
5
by: sam_cit | last post by:
Hi Everyone, I read somewhere that there are some compile time operations behind switch-case, which is why it can work for cases which evaluates to an integer or character and not strings and...
22
by: John | last post by:
Hi Folks, I'm experimenting a little with creating a custom CEdit control so that I can decide on what the user is allowed to type into the control. I started off only allowing floating point...
7
by: Rohit | last post by:
Hi, I am working on a switch module which after reading voltage through a port pin and caterogizing it into three ranges(open,low or high), passes this range to a function switch_status() with...
13
by: Satya | last post by:
Hi everyone, This is the first time iam posting excuse me if iam making any mistake. My question is iam using a switch case statement in which i have around 100 case statements to compare. so...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.