简体   繁体   中英

true/false regarding for and switch

In a C book there was a true/false question in which the following two statements were described as true.

1) Compiler implements a jump table for cases used in a switch.

2) for loop can be used if we want statements in a loop to get executed at least once.

I have following questions regarding these two points:

  • What is the meaning of statement number 1?

  • According to me, the second statement should be false, because for this task we a use a do while loop. Am I right?

The first point is somewhat misleading, if it's worded just like that. That might just be the point, of course. :)

It refers to one common way of generating fast code for a switch statement, but there's absolutely no requirement that a compiler does that. Even those that do, probably don't do it always since there's bound to be trade-offs that perhaps only make it worthwhile for a switch with more than n cases. Also the cases themselvesl typically have to be "compact" in order to provide a good index to use in the table.

And yes, a do loop is what to use if you want at least one iteration, since it does the test at the end whereas both for and while do it at the start.

1) It means that a common optimization is for a compiler to build a "jump table" which is like an array where the values are addresses of instructions where the program will execute next. The array is built such that the indexes correspond to values being switched on. Using a jump table like this is O(1), whereas a cascade of "if/else" statements is O(n) in the number of cases.

2) Sure, you can use a "do-while" loop to execute something "at least once." But you'll find that do-while loops are fairly uncommon in most applications, and "for" loops are the most common--partly because if you omit the first and third parts between their parentheses, they are really just fancy "while" loops! For example:

for (; i < x; ) // same as while (i < x)
for (i = 0; i == 0 || i < x; ) // like i = 0; do ... while (i < x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM