First I thought the compile time would take forever, or I take a weird error, but that didn’t happen the code runs for a while and then crash
This is my code:
#include <iostream>
inline void say_hello()
{
std::cout << "hello\n";
say_hello();
}
int main()
{
say_hello();
}
And I thought the compiler will convert it to something like this
#include <iostream>
int main()
{
std::cout << "hello\n";
std::cout << "hello\n";
std::cout << "hello\n";
std::cout << "hello\n";
std::cout << "hello\n";
std::cout << "hello\n";
std::cout << "hello\n";
std::cout << "hello\n";
std::cout << "hello\n";
std::cout << "hello\n";
std::cout << "hello\n";
std::cout << "hello\n";
std::cout << "hello\n";
std::cout << "hello\n";
std::cout << "hello\n";
// and crash because my storage is filled
}
But I think the compiler ignored the inline keyword
Thanks for helping
>Solution :
In modern C++, the inline specifier is only a suggestion to the compiler that you might want to inline the function. The compiler is not required to comply.
For your specific compiler, please see Visual Studio Inline Functions (C++). You seem to "want" the __forceinline decorator combined with #pragma inline_recursion(on). This will inline to a depth of 16, but that is modifiable as well. I hope it’s obvious why this is all a bad idea. Note that this is ALL compiler specific and does not apply to gcc.
__forceinline can fail for a variety of reasons, but the ones that might apply to you:
- the function is recursive (what you have) and
#pragma inline_recursion(on)is not set - the program is compiled with
/Ob0(the default for debug builds, which you might have set)
If you want to recurse to a level different than 16 (the default), you can use the inline_depth pragma to specify.
Your function would end up looking like this (untested):
#include <iostream>
#pragma inline_depth(9000)
#pragma inline_recursion(on)
__forceinline void say_hello()
{
std::cout << "hello\n";
say_hello();
}
int main()
{
say_hello();
}