删除C中的其他语句是否更有效?
该代码之间的编译器是否有任何区别:
if(something == true) {return -1}
else {return 0}
和该代码:
if(something == true) {return -1}
return 0;
编译器是否对这些代码进行不同的解释,如果是这样,则第二个示例在C中会更有效吗?
Is there any difference to a compiler between this code:
if(something == true) {return -1}
else {return 0}
and this code:
if(something == true) {return -1}
return 0;
Does the compiler interpret these differently and if so would the second example be more efficient in C?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这两个程序片段也这样做。 C编译器可以自由生成不同的(较慢或更快)代码,只要它相同。大多数C编译器将生成相同的代码,因为它们首先构建相同的中间表示形式,然后从中生成代码。
These two program snippets do the same. C compilers are free to generate different (slower or faster) code as long as it does the same. Most C compilers will generate the same code though, because they build the same intermediate representation first, and then they generate the code from that.
通常,任何现代编译器都应为诸如此类的琐碎示例生成相同的机器代码。只需观看任何编译器(例如GCC)的拆卸,启用优化并亲自查看即可。 :
https://godbolt.org/z/1kxxxsbj9s
示例 同一机器代码,甚至是人为的示例4:
也就是说,抓住输入参数并将其替换为两者的补充(
neg
),意思是1
- >-1
或0
- >0
。优化器还没有生成任何分支(条件执行路径),这会使所有高端CPU上的代码较慢。
因此,使用哪种形式主要是一种样式问题。各种安全标准(ISO 61508,ISO 26262,MISRA C等)在一个功能中倾向于在多个
返回
上皱眉,因此,如果您关心的话,xpecond> example3 可能可能实际上是最好的。
Generally any modern compiler should generate the same machine code for trivial examples such as this. Just watch the disassembly from any compiler such as gcc, enable optimizations and see for yourself. Examples:
https://godbolt.org/z/1Kxxsbj9s
All of these examples boil down to the very same machine code, even the contrived example4 one:
That is, grab the input parameter and replace it with it's two's complement (
neg
), meaning either1
->-1
or0
->0
.The optimizer also didn't generate any branch (conditional execution paths) which would have made the code slower on all high-end CPUs.
So which form to use is mostly a matter of style. Various safety standards (ISO 61508, ISO 26262, MISRA C etc) tend to quite subjectively frown at multiple
return
in a single function, so if you care about that,example3
might actually be the best one.