简体   繁体   English

对于for和switch,为真/假

[英]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. 在C书中,有一个是非题,其中以下两个陈述被描述为是。

1) Compiler implements a jump table for cases used in a switch. 1)编译器为开关中使用的情况实现跳转表。

2) for loop can be used if we want statements in a loop to get executed at least once. 2)如果我们希望循环中的语句至少执行一次,则可以使用for循环。

I have following questions regarding these two points: 关于这两点,我有以下问题:

  • What is the meaning of statement number 1? 1号陈述的含义是什么?

  • According to me, the second statement should be false, because for this task we a use a do while loop. 根据我的说法,第二条语句应该为false,因为对于此任务,我们使用do while循环。 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. 它指的是为switch语句生成快速代码的一种常见方式,但是绝对不要求编译器这样做。 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. 即使是那些,可能不会因为必然是取舍,也许只有使它值得一做的总是 switchn个个案多。 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. 是的,如果需要至少一次迭代,则使用do循环,因为它在最后进行测试,而forwhile则在开始进行测试。

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. 1)这意味着对于编译器来说,常见的优化是建立一个“跳转表”,该跳转表就像一个数组,其中的值是程序接下来将要执行的指令的地址。 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. 使用这样的跳转表为O(1),而级联“ if / else”语句的个数为O(n)。

2) Sure, you can use a "do-while" loop to execute something "at least once." 2)当然,您可以使用“ do-while”循环执行“至少一次”操作。 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! 但是您会发现do-while循环在大多数应用程序中并不常见,“ for”循环是最常见的-部分原因是,如果省略括号之间的第一部分和第三部分,它们实际上只是“ while”而已循环! For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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