Reputation: 8591
Consider the classic way of defining a factorial function:
#include <stdio.h>
__attribute__((always_inline)) inline int factorial(int n)
{
if (n == 1){
return 1;
} else {
return n * factorial(n - 1);
}
}
int main()
{
printf("value %d", factorial(7/*guaranteed to not overflow int*/));
}
I'm forcing my compiler (gcc) to inline the factorial function. That should cause a problem. gcc is ignoring my force inline without error. Is this expected?
Upvotes: 4
Views: 942
Reputation: 65720
From GCC's documentation:
GCC does not inline any functions when not optimizing unless you specify the
always_inline
attribute for the function.
So always_inline
doesn't mean "inline this or diagnose", it means "inline even if optimizations are off". It will still refuse to inline something if it's not possible or reasonable.
As you can see here, for an example as simple as yours the whole function can be optimised out and the result calculated at compile-time. Even if the argument is not a compile-time constant, the function can still be inlined. Recursion doesn't always make inlining impossible.
However, as pointed out by Floris Velleman, if you turn optimizations off it will fail to compile, stating that the function is not considered for inlining, even though it will inline it if optimizations are on. Seems like the actual handling of the attribute is not fully consistent with the documentation.
Upvotes: 4