I have created a very simple x86
console program that uses Visual Studio 2019 compiler
to sum 2 numbers just to see how is the program be after disassembly but I found something unclear to me.
// C++
#include <iostream>
int sum(int n, int n2) {
return n + n2;
}
int main() {
int result = sum(7, 3);
std::cout << result;
}
After disassembled
; The main function from outside
Push edi
push esi
push dword ptr ds:[eax]
call <consoleapplication._main>
add esp, C
; The main function from inside
mov ecx, dword ptr ds : [<&? cout@std@@3V ? $basic_ostream@DU ? $char_traits@D@std@@@1@A>]
push A
call dword ptr ds : [<&? ? 6 ? $basic_ostream@DU ? $char_traits@D@std@@@std@@QAEAAV01@H@Z>]
xor eax, eax
ret
As you have seen in the second code block, the second line
push A
That is the result of the "sum" function but where is its body and where is the call instruction that calls it in the main function?
static inline
in C++ has a similar effect. Usually the function body will be completely inlined. In your case, however, the compiler knewsum()
was only called once. It knew it was called with known (literal) arguments and so there was no point in delegating the computation to runtime. Essentially your example isconstexpr
without explicitly saying it. Optimizers in compilers these days are fairly smart and will catch much more convoluted cases (but fail with some trivial ones, too). Change the code to take inargc
frommain()
and it should look different.static inline
on a function is one way to nudge the compiler in the right direction without using proprietary "attributes" like__forceinline
.