Let's say I have a function
bool inline fn(int a) {
if (a == 0) {
a = 1; //or some other computation
return true;
}
return false;
}
int main() {
int a = 0;
if (fn(a)) {
return 1;
}
}
will the main
code be roughly inlined to:
int a = 0;
bool test = false;
if (a == 0) {
a = 1; //or some other computation
test = true;
}
if (test) {
return 1;
}
thus resulting in two ifs, OR rather it would look more like this:
int a = 0;
if (a == 0) {
a = 1; //or some other computation
return 1;
}
which I obviously wanted to achieve. I'm using functions here not to make the executable smaller or anything, but purely to make the code more readable.
Actually why I do this is in the next example – imagine the function fn is templated, so that I can choose of more implementations of the function, while having the caller function exhibiting common behavior to all it's template instances, delegating the specific functionality to called functions.
Again this usage is purely for code reuse and readability. The functions will called/inlined in a single place in the code (that is the base_function).
I want to know, if tests on return values of the functions are efficiently optimized, so this code reuse technique doesn't interfere with performace/ actual execution at all.
template<typename TagSwitch, typename ... Args>
void base_function(Args ... args) {
// some base behavior meant to be common to all functions "derived" from this function
if (do_end(TagSwitch(), args ...)) {
return;
}
//specific_behavior(TagSwitch(), args ...);
}
// default for all specific ("derived") functions is don't end
template<typename TagSwitch, typename ... Args>
bool inline do_end(TagSwitch, Args ... args) {
return false;
}
// here I define my specific ("derived") function
struct MySpecificFunctionTag {};
template<typename ... Args>
bool inline do_end(MySpecificFunctionTag, int a, Args ... args) {
if (a == 0) {
//Do something (set a parameter)
return true;
}
return false;
}
int main() {
base_function<MySpecificFunctionTag>(1);
}
I'd like to know, if the test if (do_end(TagSwitch(), args ...)) {
in base_function<MySpecificFunctionTag>(1)
instantiation would result in two ifs or one would be optimized out.