473,598 Members | 2,916 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

switch case to a jump table

Hi Everyone,

I wanted to know as to how a switch case like the following one is
converted into a jump table by the compiler, assuming that it does,

switch(i)
{
case 4 : {
...
printf("4");
break;
}
case 5:
case 6:
{
printf("56");
break;
}
case 1000: {
printf("1000");
break;
}
default : {
printf("default ");
break;
}
};

May 7 '07 #1
9 10989

<sa*****@yahoo. co.inwrote in message
news:11******** **************@ p77g2000hsh.goo glegroups.com.. .
Hi Everyone,

I wanted to know as to how a switch case like the following one is
converted into a jump table by the compiler, assuming that it does,

switch(i)
{
case 4 : {
...
printf("4");
break;
}
case 5:
case 6:
{
printf("56");
break;
}
case 1000: {
printf("1000");
break;
}
default : {
printf("default ");
break;
}
};
The compiler can grab 1001 * size of function pointer bytes of memory, and
construct a lookup table. It may or may consider the tradeoff to be worth
it.

Alternatively it can look for a function that converts the integer values
into unique keys with a limited range. In this case it would be something
like (x/100 + x % 10). The technical term is "perfect hashing". The second
approach is much more difficult to implement and I don't know if any
compilers actually use it, though I suspect they do.
--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

May 7 '07 #2
sa*****@yahoo.c o.in wrote:
I wanted to know as to how a switch case like the following one is
converted into a jump table by the compiler, assuming that it does,

switch(i)
{
case 4 : {
...
printf("4");
break;
}
case 5:
case 6:
{
printf("56");
break;
}
case 1000: {
printf("1000");
break;
}
default : {
printf("default ");
break;
}
};
There are no requirements in C for how a compiler implements a switch
statement.

Many different techniques are used in practice. What I expect is that
when a compiler decides to use a lookup table, it first decides on the
bounds of the table. At run time, the code checks the switch argument
value against the bounds, and if within the table, looks up the address.
For your particular example, I would expect most compilers to not use
a table.
--
Thad
May 7 '07 #3
<sa*****@yahoo. co.inwrote in message
news:11******** **************@ p77g2000hsh.goo glegroups.com.. .
I wanted to know as to how a switch case like the following one is
converted into a jump table by the compiler, assuming that it does,

switch(i)
{
case 4 : {
...
printf("4");
break;
}
case 5:
case 6:
{
printf("56");
break;
}
case 1000: {
printf("1000");
break;
}
default : {
printf("default ");
break;
}
};
I doubt a decent compiler would use a jump table for this; it's way too
sparse. Still, if it did, the asm would look something like this
pseudocode:
void *jumptable[1001] = { default, default, default, default, label4,
label56, label56, default, ... , default, label1000 };
/* insert your code to set i */
goto jumptable[i];
label4:
printf("4");
goto end;
label56:
printf("56");
goto end;
label1000:
printf("1000");
goto end;
default:
printf("default ");
end:
S

--
Stephen Sprunk "Those people who think they know everything
CCIE #3723 are a great annoyance to those of us who do."
K5SSS --Isaac Asimov
--
Posted via a free Usenet account from http://www.teranews.com

May 7 '07 #4
On May 7, 6:22 pm, "Stephen Sprunk" <step...@sprunk .orgwrote:
<sam_...@yahoo. co.inwrote in message

news:11******** **************@ p77g2000hsh.goo glegroups.com.. .


I wanted to know as to how a switch case like the following one is
converted into a jump table by the compiler, assuming that it does,
switch(i)
{
case 4 : {
...
printf("4");
break;
}
case 5:
case 6:
{
printf("56");
break;
}
case 1000: {
printf("1000");
break;
}
default : {
printf("default ");
break;
}
};

I doubt a decent compiler would use a jump table for this; it's way too
sparse. Still, if it did, the asm would look something like this
pseudocode:

void *jumptable[1001] = { default, default, default, default, label4,
label56, label56, default, ... , default, label1000 };
/* insert your code to set i */
goto jumptable[i];
label4:
printf("4");
goto end;
label56:
printf("56");
goto end;
label1000:
printf("1000");
goto end;
default:
printf("default ");
end:

S

--
Stephen Sprunk "Those people who think they know everything
CCIE #3723 are a great annoyance to those of us who do."
K5SSS --Isaac Asimov

--
Posted via a free Usenet account fromhttp://www.teranews.co m- Hide quoted text -

- Show quoted text -
How would that work with negative values of i?

Moreover, it is correct to assum that,

case 5: printf("56");
break;
case 6: printf(56");
break;

is same for the jump table generation for the following switch case?

case 5:
case 6:
printf("56");
break;

Thanks in advance!!!

May 7 '07 #5
In article <11************ **********@e51g 2000hsg.googleg roups.com>,
<sa*****@yahoo. co.inwrote:
>void *jumptable[1001] = { default, default, default, default, label4,
label56, label56, default, ... , default, label1000 };
/* insert your code to set i */
goto jumptable[i];
....
>How would that work with negative values of i?
It wouldn't, not for values above 1000. Unless the compiler can
determine that the value is in range, it has to check it.

-- Richard

--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
May 7 '07 #6
><sa*****@yahoo .co.inwrote in message
>news:11******* *************** @p77g2000hsh.go oglegroups.com. ..
>I wanted to know as to how a switch case like the following one is
converted into a jump table by the compiler, assuming that it does ...
[code snipped, but the range for the selector was 4..1000]

In article <46************ ***********@fre e.teranews.com>
Stephen Sprunk <st*****@sprunk .orgwrote:
>I doubt a decent compiler would use a jump table for this; it's way too
sparse.
Yes, although as Richard Heathfield noted, one can apply a reduction
function first. (This complicates the code since each match must
then reject false hits.)
>Still, if it did, the asm would look something like this
pseudocode:

void *jumptable[1001] = { default, default, default, default, label4,
label56, label56, default, ... , default, label1000 };
Actually, more like:

static void *const __table[1000 - 4 + 1] =
{ &&__label4, &&__label56, &&__label56,
&&__label_defau lt, ..., &&__label_defau lt, &&__label100 0 };

(using gcc's "&&label" syntax), and:
>/* insert your code to set i */
goto jumptable[i];
replace this "goto" with:

if (i >= 4 && i <= 1000) goto __table[i - 4];
goto __label_default ;

or (closer to typical machine code):

if ((%t0 = i - 4) < 0) goto __label_default ;
if (%t0 1000 - 4) goto __label_default ;
goto __table[%t0];

(where %t0 is a "compiler's temporary values" machine register).

The specifics are quite machine-dependent, but in general, there
are two criteria for using a jump table: the "load factor" (or
"fill factor" or other similar name) has to be high enough, typically
at least 2/3 -- i.e., most of the table-slots must not be the
"default:" label, or if there is no default, the internally-generated
"end of switch" label (which is then used as the default) -- and
there must be some minimum number of target labels (typically at
least 3 to 5).

If the number of labels is very low, a simple compare/goto sequence
is usually best.

If the number of labels is high but the table is sparse, the compiler
should:

- break up the cases into contiguous sub-ranges
- use a hash system
- use a binary search
- use an interpolative search

and/or some combination of all of the above. For instance, if we
have cases 0, 1, 2, 3, 4, 6, 100, 9000, 9001, 9002, 9003, and 15000,
we might want machine code like:

if (i 100) {
if (i == 15000) goto __label_15000;
if (i < 9000 || i 9003) goto __label_default ;
goto __table9000[i - 9000];
} else if (i == 100)
goto __label_100;
else if (i < 0 || i >= 6)
goto __label_default ;
else
goto __table0[i - 0];

(I am not sure how often interpolative search would pay off.
Probably not often -- most cases where it would, would be
subsumed by a jump table.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
May 7 '07 #7
Chris Torek said:

<snip>
In article <46************ ***********@fre e.teranews.com>
Stephen Sprunk <st*****@sprunk .orgwrote:
>>I doubt a decent compiler would use a jump table for this; it's way
too sparse.

Yes, although as Richard Heathfield noted, one can apply a reduction
function first.
Chris, I noted no such thing. (And of course you err too infrequently
for anyone to pass up the chance of correcting you, no matter how
trivial the slip.)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
May 7 '07 #8
sa*****@yahoo.c o.in writes:
I wanted to know as to how a switch case like the following one is
converted into a jump table by the compiler, assuming that it does,

switch(i)
{
case 4 : {
...
printf("4");
break;
}
case 5:
case 6:
{
printf("56");
break;
}
case 1000: {
printf("1000");
break;
}
default : {
printf("default ");
break;
}
};
Who cares?

The generated code, assuming a properly working compiler, will produce
the specified output for any value of i. It could use a jump table, a
sequence of conditional jumps, or a virtual flux capacitor. The
standard says exactly nothing about how this is done; it specifies
only the behavior of the final program.

If you're curious about what code is generated by a particular
compiler, you can compile the code with your own compiler and examine
the code it generates (typically "-S" tells the compiler to generate
an assembly listing; check your compiler's documentation). If you
want to know how compilers handle this in general, comp.compilers is
probably a better place to ask.

--
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."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
May 7 '07 #9
On Mon, 07 May 2007 19:17:48 +0000, Richard Heathfield wrote:
>Chris Torek said:
<snip>
>In article
Stephen Sprunk wrote:
>>>I doubt a decent compiler would use a jump table for this; it's way
too sparse.

Yes, although as Richard Heathfield noted, one can apply a reduction
function first.

Chris, I noted no such thing. (And of course you err too infrequently
for anyone to pass up the chance of correcting you, no matter how
trivial the slip.)
there are people that "err infrequently" but i, you, all ones, make
errors the same it is possible not to be said for some program
May 10 '07 #10

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

Similar topics

35
8325
by: Thomas Matthews | last post by:
Hi, My son is writing a program to move a character. He is using the numbers on the keypad to indicate the direction of movement: 7 8 9 4 5 6 1 2 3 Each number has a direction except for '5'. So in his switch statement, he omits a case for '5':
8
6811
by: Dave | last post by:
Hello all, Consider the case of an if with many else if clauses vs. a switch with many cases. In thinking about how such control constructs would likely be implemented, it would seem that neither would be superior to the other in terms of execution speed of the generated code. Would others agree that this is true for "typical" implementations?
4
6903
by: Gurikar | last post by:
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
17
2807
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
3752
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 ?
12
3217
by: junky_fellow | last post by:
Which is better using a switch statement or the if-then equivalent of switch ?
65
6651
by: He Shiming | last post by:
Hi, I just wrote a function that has over 200 "cases" wrapped in a "switch" statement. I'm wondering if there are performance issues in such implementation. Do I need to optimize it some way? In terms of generated machine code, how does hundreds of cases in a switch differ from hundreds of if-elses? Do compilers or processors do any optimization on such structured code? Do I need to worry about the performance, usually?
11
2514
by: Smithers | last post by:
Just wondering if the sequence of the case(s) in the switch block might impact performance. Suppose I switch on an int, and I have 4 expected cases. Lets say I expect case 3 to happen 95% of the time. Would the switch block be expected to execute faster (meaning "start executing the code for case 3 sooner") when case 3 appears first, as opposed to appearing as the 3rd case:, as in the following code? switch (someInt) { case 3:
5
4742
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!!!
0
7981
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
7894
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
8392
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...
0
8262
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
6711
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...
1
5847
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
5437
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
3894
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
1245
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.