简体   繁体   English

内联函数中的分支

[英]Branches in Inline Functions

I think I have a serious compiler mistrust. 我认为我有严重的编译器不信任。 Do branches inside inline functions get optimized out if they have constant results? 如果内联函数的分支有不变的结果,它们是否会被优化掉?

For the example function: 对于示例函数:

#define MODE_FROM_X_TO_Y 0
#define MODE_FROM_Y_TO_X 1

inline void swapValues(int & x, int & y, int mode) {
    switch(mode) {
        case MODE_FROM_X_TO_Y:
            y = x;
            break;
        case MODE_FROM_Y_TO_X:
            x = y;
            break;
    }
}

Would: 将:

swapValues(n,m,MODE_FROM_X_TO_Y);

be optimized as: 被优化为:

n = m;

First off, it won't even compile (until you add a return type). 首先,它甚至不会编译(直到你添加一个返回类型)。

Secondly, swap is an awesomely badly chosen name (since it doesn't do a swap , and conflicts with the std::swap name). 其次, swap是一个非常糟糕的选择名称(因为它不进行swap ,并且与std::swap名称冲突)。

Thirdly, head over to http://gcc.godbolt.org/ : 第三,转到http://gcc.godbolt.org/

Live On Godbolt 活在Godbolt上

在此输入图像描述

Generally speaking, the answers to these questions are compiler dependent. 一般来说,这些问题的答案取决于编译器。

To get an answer to your question with your code, with your compiler (and compiler version), and compiler settings (eg optimisation flags) you will need to examine the code output by the compiler. 要使用您的代码,编译器(和编译器版本)以及编译器设置(例如优化标志)来回答您的问题,您需要检查编译器输出的代码。

Branches in any code - not just within inlined functions - can potentially be "optimized out" if the compiler can detect that the same branch is always followed. 如果编译器可以检测到始终遵循相同的分支,则任何代码中的分支(不仅仅是内联函数内)都可能被“优化”。

Some modern compilers are also smart enough to not inline a function declared inline if it evaluates another function as a better candidate for inlining. 一些现代编译器也非常聪明,如果它将另一个函数作为内联的更好候选者进行评估,则不能内联声明为inline联的函数。 A number of modern compilers can do a better job making such decisions than a typical C/C++ programmer. 与典型的C / C ++程序员相比,许多现代编译器可以做出更好的决策。

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

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