473,698 Members | 1,901 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Switch() vs if else if

Whats the difference b/w swicth case and if else if.
Iam finding both are same when you are using in application. Only
difference if else if more flexible to use with all data types. But
some people says switch case is faster than if else if, i dont know is
it and why is it??

Regards

Jul 23 '05 #1
4 6904
Gurikar wrote:
Whats the difference b/w swicth case and if else if.
The former can only used with integral types, and the case values need to be
compile-time constants. An if/else cascade is likely to be slower than
switch/case.
Iam finding both are same when you are using in application. Only
difference if else if more flexible to use with all data types. But
some people says switch case is faster than if else if, i dont know is
it and why is it??


Heh, I wrote the above before I read this. Well, the reason is that
switch/case is often implemented using a jump table with the case values as
index into the table. The if/else is usually implemented using a cascade of
conditional jumps.

Jul 23 '05 #2

"Gurikar" <ms*******@gmai l.com> wrote in message
Whats the difference b/w swicth case and if else if.
Iam finding both are same when you are using in application. Only
difference if else if more flexible to use with all data types. But
some people says switch case is faster than if else if, i dont know is
it and why is it??


Well, you could read about jump table optimization. But measure and then
only believe what you read.

Sharad

Jul 23 '05 #3
Gurikar wrote:
Whats the difference b/w swicth case and if else if. How about a jump table, too?

The switch statement only handles integral quantities.
Compilers may optimize the switch statement into a jump table
(see below).

An if-else-if ladder can handle any type, such as a string.
This construct is more difficult for a compiler to optimize.

A jump table is either a table of addresses (pointers) or
jump instructions. An index is used to access the appropriate
location, then an action is taken. This can be implemented
in C++ using an std::map of <key, function_pointe r> or an
array of similar structures.

Iam finding both are same when you are using in application. Only
difference if else if more flexible to use with all data types. But
some people says switch case is faster than if else if, i dont know is
it and why is it?? Only believe "faster than" when actual profiling has been
performed. And only worry about "faster" when the program
is too slow.


Regards

The best construct to use is the one that is the easiest
to understand to the reader.

I prefer to use jump tables, because the data can change
without having to retest the jump-table driver (engine).

All these constructs depend on the situation.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library
Jul 23 '05 #4

Gurikar wrote:
Whats the difference b/w swicth case and if else if.
Iam finding both are same when you are using in application. Only
difference if else if more flexible to use with all data types. But
some people says switch case is faster than if else if, i dont know is it and why is it??

Regards


Besides the obvious jumptables, compilers can also generate nested
if-else constructs instead of lineair if-elseif chains. In fact,
these can be mixed.

Asumme you have cases 1..10 and 101..110. Now, a jumptable might be
inconvenient, but implementing such a switch internally as a single
if(x<10) __goto jump[x] else if (x>100&&x<110) __goto jump[x-90]
is certainly legal. Let the compiler deal with those details.

If you would write such code, you'd have to review it every time you
add an enumerator. So does a compiler, but it's a lot faster and
makes less mistakes. Besides, if you did that your source becomes
unreadable. If the compiler does this to your switch, only the
assembly becomes unreadable.

Regards,
Michiel Salters

Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
7598
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 (>0): case (<0):
10
9577
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 'case' code snippet does not. (the code's function is illustrative.) ////////////////////////////////////////// //////// working 'if/else' switch //////// //////////////////////////////////////////
17
2813
by: prafulla | last post by:
Hi all, I don't have a copy of C standard at hand and so anyone of you can help me. I have always wondered how switch statements are so efficient in jumping to the right case (if any)? Can anybody point me to the innards of it please? Sorry if this is OT on clc and more relevant to comp.compilers. I am confused here too.
11
3761
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 the assembly level ? for a performance critical application is it better to to use switch case or accomplish the same using fn pointers ?
18
3061
by: swaroophr | last post by:
Which of switch statement and if-else statement takes less time to execute?
13
7543
by: Michael Griebe | last post by:
Simple question. I am optimizing some C++ code and I'd like to know which is faster (or if there is any difference at all) between using a switch statement or nested else-ifs. I'm partial to else-if. I know to put the if statement that is most likely to be true at the top of the else-if chain -so as to minimize checks. I've searched around online and mainly found answers to this question for Java programmers. Thanks in advance,...
10
12319
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 program to demonstrate how a switch without breaks behaves vs. how I expected it to behave. The code includes: (1) a switch statement with breaks (2) the if/else statements that have the same results as (1) (3) a switch statement without breaks...
5
4746
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 that it makes switch-case faster than if-else statements, is it true and if so what is the underlying concept behind a switch-case compilation? Can anyone help in this regard. Thanks in advance!!!
7
3357
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 parameters value and signal ID. Signal Id is used to get a user configurable parameter inside a configuration file, which depends on the type of switch. I have implemented it as under. Please ignore those magic numbers as I have mimized logic to...
13
11813
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 just curious to find out is it effective to use this method?? or is there is any other alternative method present so that execution time and code size can be reduced?? Thanks in advance.
0
8672
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8600
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9156
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8892
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8860
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7712
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3038
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2323
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.