473,725 Members | 2,053 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

which is better "switch" or "if-else"

Which is better using a switch statement or the if-then equivalent
of switch ?

Nov 14 '05 #1
12 3231
Hi

It depends on the the conditions. If you just have int or char
constants as the value of the expression then switch statement is
concise and easy to read.

However if you have comples values and/or multiple ranges then if
condition is better.

If you give us an example of your problem then possibly someone could
tell you which is betetr to use.

Nov 14 '05 #2
ju**********@ya hoo.co.in wrote:
Which is better using a switch statement or the if-then equivalent
of switch ?


Define "better".
You can do things with switch statements and fallthrough cases that
are awkward with if/(else if/)else blocks. On the other hand,
switch works only for integers and accepts only constants for the
case labels.

As remarked in another reply: Tell us what you want to achieve
and we can comment in more detail on the pros and contras.

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #3

Michael Mair wrote:
ju**********@ya hoo.co.in wrote:
Which is better using a switch statement or the if-then equivalent
of switch ?


Define "better".
You can do things with switch statements and fallthrough cases that
are awkward with if/(else if/)else blocks. On the other hand,
switch works only for integers and accepts only constants for the
case labels.

As remarked in another reply: Tell us what you want to achieve
and we can comment in more detail on the pros and contras.


I read somewhere that assembly of switch generates jump tables
and is faster as compared to if-then equivalent.

Nov 14 '05 #4
On 16 May 2005 06:06:11 -0700, ju**********@ya hoo.co.in
<ju**********@y ahoo.co.in> wrote:
Michael Mair wrote:
ju**********@ya hoo.co.in wrote:
> Which is better using a switch statement or the if-then equivalent
> of switch ?


Define "better".
You can do things with switch statements and fallthrough cases that
are awkward with if/(else if/)else blocks. On the other hand,
switch works only for integers and accepts only constants for the
case labels.

As remarked in another reply: Tell us what you want to achieve
and we can comment in more detail on the pros and contras.


I read somewhere that assembly of switch generates jump tables
and is faster as compared to if-then equivalent.


It may, it may not. It depends on your compiler (not just the make,
different versions of the same compiler may generate different code),
the optimisations selected, the capabilities of your hardware, the
number and values of the case constants, and probably a load of other
things.

The same is true for most other "which is faster/smaller" questions, the
answer is "it depends". If you really want to know, for your specific
system, write programs to test it...

(I wrote an optimiser for MSDOS 'TSR' programs once which attempted to
solve the "small as possible" problem for switches. Then I found that
it was different on a 286 to an 8086...)

Chris C
Nov 14 '05 #5
>> As remarked in another reply: Tell us what you want to achieve
and we can comment in more detail on the pros and contras.


I read somewhere that assembly of switch generates jump tables
and is faster as compared to if-then equivalent.


Any statement of the form "A is faster than or slower than or about the
same speed as B" is probably false if you don't specify the hardware,
compiler and version, and OS and version.

Maybe the compiler generates a jump table. I doubt it would in this case:

switch(fark) {
case 0x7fffffff: ...; break;
case 0: ...; break;
case 0x40003726: ...; break;
case 0x80000007: ...; break;
default: ...; break;

since the jump table would likely exceed available address space on
a machine with 32-bit integers and a 32-bit address space.

Compilers can use various strategies: sequential if-then-else,
jump table, or binary search (nested if-then-else), and they can
use different strategies for parts of the search space. For example,
if you have a switch with 20 different values in the range 'a' ..
'z', plus EOF, it could do the EOF with if-then-else, and use a
jump table for the rest of it where the values are densely packed
together. A jump table (with initial range checking) probably isn't
worth it if the switch has few cases, e.g. less than 3 - 10.

Gordon L. Burditt

Nov 14 '05 #6
On 16 May 2005 06:06:11 -0700, in comp.lang.c ,
ju**********@ya hoo.co.in wrote:

Michael Mair wrote:
ju**********@ya hoo.co.in wrote:
> Which is better using a switch statement or the if-then equivalent
> of switch ?


Define "better".
You can do things with switch statements and fallthrough cases that
are awkward with if/(else if/)else blocks. On the other hand,
switch works only for integers and accepts only constants for the
case labels.

As remarked in another reply: Tell us what you want to achieve
and we can comment in more detail on the pros and contras.


I read somewhere that assembly of switch generates jump tables
and is faster as compared to if-then equivalent.


maybe. Maybe not. This is entirely dependent on your hardware and how
good your compiler is at optimising. Learn the three rules of
optimisation before proceeding.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt >
Nov 14 '05 #7
ju**********@ya hoo.co.in writes:
Which is better using a switch statement or the if-then equivalent
of switch ?


The switch statement has restrictions that if-then doesn't. A switch
statement compares a single integer value to a number of compile-time
constant values; an if-then can evaluate any arbitrary condition.

As a matter of style, if you *can* use a switch, you probably should
use the switch rather than the equivalent if-then-else chain -- unless
there are only one or two choices.

If you're concerned about performance, don't be. Any decent compiler
should generate good code for any switch or if-then-else statement.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #8
ju**********@ya hoo.co.in writes:
Which is better using a switch statement or the if-then equivalent
of switch ?


The better choice is the one that results in code that is easier
to read.
--
Ben Pfaff
email: bl*@cs.stanford .edu
web: http://benpfaff.org
Nov 14 '05 #9
ju**********@ya hoo.co.in wrote:
# Which is better using a switch statement or the if-then equivalent
# of switch ?

Which is easier to understand in your code?

As far as which is more efficient, simply by posting this question, you have
already used up more cpu cycles and burnt out more electrons than your
program would ever save by being more 'efficient'.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
One of the drawbacks of being a martyr is that you have to die.
Nov 14 '05 #10

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

Similar topics

10
54597
by: qazmlp | last post by:
There are some blocks of C/C++ code put under #if 0 #end if Is there anyway to make the code inside these blocks to get executed (may be by using some command line options)?
4
11435
by: Clint | last post by:
All, I can't seem to find a solution to this problem. I'm not sure if this is a Visual Studio problem, a .NET Framework problem, an IIS problem, or an ASP.NET problem, so please stick with me ... I had Visual Studio (the original) installed on my XP workstation. When Visual Studio 2003 came out, I installed that as well, leaving the old Visual Studio in place. All this time, I had no problems running ASP.NET apps, whether running...
28
7394
by: robert | last post by:
In very rare cases a program crashes (hard to reproduce) : * several threads work on an object tree with dict's etc. in it. Items are added, deleted, iteration over .keys() ... ). The threads are "good" in such terms, that this core data structure is changed only by atomic operations, so that the data structure is always consistent regarding the application. Only the change-operations on the dicts and lists itself seem to cause problems...
12
2044
by: spibou | last post by:
Why is a pointer allowed to point to one position past the end of an array but not to one position before the beginning of an array ? Is there any reason why the former is more useful than the later ? Spiros Bousbouras
2
6860
NewYorker
by: NewYorker | last post by:
Write a switch statement that tests the value of the char variable response and performs the following actions: if response is y , the message Your request is being processed is printed if response is n , the message Thank you anyway for your consideration is printed if response is h , the message Sorry, no help is currently available is printed for any other value of response , the message Invalid entry; please try again is...
0
1368
by: Sudz28 | last post by:
Greetings! I am attempting to write a program that will allow a user to manipulate data read from a file, and am obviously in no way near finished. However, one problem I'm having that I don't understand is with my switch subroutine. In the below code, if I select "d" or anything that is an invalid response, it loops correctly back to the menu. However, if I attempt to insert (i), find (f), or delete (d) it loops back to the menu *but*...
21
7851
by: comp.lang.tcl | last post by:
set php {<? print_r("Hello World"); ?>} puts $php; # PRINTS OUT <? print_r("Hello World"); ?> puts When I try this within TCL I get the following error:
8
11149
by: Dom | last post by:
This is a little tricky, but I think the error I'm getting isn't valid. The compiler just doesn't know my logic. MyObject o; switch (IntVariable) { case 1: o = new MyObject() break;
18
3639
by: desktop | last post by:
I have 3 types of objects: bob1, bob2 and bob3. Each object is identified by a unique ID which gets returned by the function getId(). All bobs are descendants from class BaseBob which is an abstract class that has the virtual function getId(). I then have a function that prints a special string when a bob meets another bob (all combinations of bobs has to meet and since the are schizophrenic they can also meet themselves):
4
1462
by: javelin | last post by:
I'm defining several arrays in the following format: $farmanimals = array('farmanimal1' ='horse', 'farmanimal2' ='cow', 'farmanimal3' ='chicken') $housepets = array('housepet1' ='dog', 'housepet2' ='cat', 'housepet3' ='bird') $zooanimals = array('zooanimal1' ='monkey', 'zooanimal2' ='lion', 'zooanimal3' ='zebra', 'zooanimal4' ='giraffe') I'm then running through a long text file, and detecting what part of
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9174
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,...
1
6702
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
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();...
0
4517
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4782
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3221
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
2634
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.