是“} while (0);”总是等于“break;} while (1);”?
我比较了 gcc 汇编器的输出
do {
// some code
} while (0);
和
do {
// some code
break;
} while (1);
输出是相等的,无论有没有优化,但是..
总是这样?
没有实验可以证明理论,只能证明它们是错误的
I have compared gcc assembler output of
do {
// some code
} while (0);
with
do {
// some code
break;
} while (1);
The output is equal, with or without optimization but..
It's always that way?
No experiment can prove theories, they can only show they are wrong
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
有一点细微的差别:
当
condition
为 true 时将重新启动循环,而在} while(0);
版本中,continue
将相当于break
。如果不存在
Continue
,那么它们应该生成完全相同的代码。There is a slight difference:
Will restart the loop when
condition
is true, whereas in the} while(0);
version, thecontinue
will be equivalent tobreak
.If no
continue
is present, then they should produce exactly the same code.这些形式并不等同。这是一个无限循环:
这不是:
The forms are not equivalent. This is an infinite loop:
This isn't:
编辑:在阅读有关此事的各种评论后,我承认这个答案是错误的。对不起。
而不是:
或:
我只是使用:
我不是 100% 确定你是否可以在 C++ 中执行此操作,但如果你想限制变量的范围,这就是你这样做的原因,只需使用花括号即可他们自己:
Edit: Upon reading various comments on the matter, I will admit that this answer is wrong. Sorry.
Instead of:
or:
I would just use:
I'm not 100% sure if you can do this in c++, but if you want to limit the scope of variables, and that is why you are doing this, just use curly braces by themselves:
马库斯的评论向我指出了这个答案:区别在于使用
continue
关键字时。在这种情况下:
您将获得仅一次迭代,而在这种情况下:
您将获得30次迭代。在VS2008下测试。
Markus' comment pointed me to this answer: the difference is when using
continue
keyword.In this case:
you get only one iteration, while in this case:
you get 30 iterations. Tested under VS2008.
do while 子句在逻辑上是等效的。它们是否被翻译成相同的字节码取决于手头的编译器。我想大多数现代编译器都会平等地对待它们。
The do while clauses are logically equivalent. If they are translated to the same byte code depends on the compiler at hand. I guess that most modern compilers will treat them equally.
根据您的评论进行编辑,您在
break
中使用了 while ,以便在满足某些条件时能够跳出“循环”。如果这是您想要实现的目标:
...那么只需将 while 循环中的代码分解为具有多个返回的独立函数即可:
EDIT based on your comment that you're using a while with
break
s in order to be able to break out of the 'loop' when certain conditions have been met.If this is what you're trying to accomplish:
...then just break the code you have in your while loop out to a stand-alone function with multiple returns: