Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

In high standard compilers, could inline do the job of the constexpr everytime?

47 views
Skip to first unread message

chris...@engineer.com

unread,
Aug 9, 2018, 8:27:42 AM8/9/18
to
For example:

//--------------------- a.cpp ------------------------

#include <iostream>

#ifdef TEST1

inline int fac(int n)
{
return n<2? 1 : n*fac(n-1);
}

#else

constexpr int fac(int n)
{
return n<2? 1 : n*fac(n-1);
}

#endif

int main()
{
std::cout << fac(6) << std::endl;

return 0;
}

// --------------------end a.cpp---------------------


$ g++ -O3 a.cpp -S -o a1.s -DTEST1
$ g++ -O3 a.cpp -S -o a2.s -DTEST2
$ diff a1.s a2.s
$
(That is, there is not difference between a1.s and a2.s)

Code snippet of a1.s (which is equal to a2.s):

[...]
.cfi_startproc
subq $8, %rsp
.cfi_def_cfa_offset 16
movl $720, %esi
movl $_ZSt4cout, %edi
call _ZNSolsEi
[...]

As you can see, the fac(6) was completly inlined (in both cases there is a literal 720).

That gives the feeling that inline could do constexpr's job.

Bo Persson

unread,
Aug 9, 2018, 8:56:22 AM8/9/18
to
You don't use the result in a constant expression, so there IS no
difference.

If you did, the constexpr version would work as it is required to result
in a compile time constant.

The inline version is only ALLOWED to be evaluated at compile time, not
required. But why would the compiler bother to do it differently?


Bo Persson

Öö Tiib

unread,
Aug 9, 2018, 12:58:15 PM8/9/18
to
On Thursday, 9 August 2018 15:56:22 UTC+3, Bo Persson wrote:
>
> The inline version is only ALLOWED to be evaluated at compile time, not
> required. But why would the compiler bother to do it differently?

Compilers do it differently when optimizations are turned off.
It is for to let confused developer to step through the code with
debugger in hope to realize where their logic error is.

Juha Nieminen

unread,
Aug 10, 2018, 4:59:58 AM8/10/18
to
chris...@engineer.com wrote:
> That gives the feeling that inline could do constexpr's job.

Theoretically the result of a constexpr function (or other expression)
can be used in places where a compiler-time constant is required
(such as the size of a static array inside a class or struct,
or an integral template parameter). The result of an inline function
can never be used in this manner.

(Of course there's the caveat that the standard doesn't guarantee
that constexpr functions will be evaluated at compile time, which
makes this a bit of a problem. However, in code that's not supposed
to be universally compilable I have used constexpr functions for
truly compile-time constant evaluation.)
0 new messages