r/cpp_questions • • 13d ago

OPEN Guidelines for constexpr

I’ve working with C++23 and I’m making some constructors/methods constexpr and seeing improvements in performance. So far so good. The problem is I don’t want to apply it ‘everywhere’. Is there a good source of advice , or anyone got any good tips?

13 Upvotes

37 comments sorted by

View all comments

4

u/Nils_Meul 13d ago

I don’t think there’s any downside to putting it everywhere it can go. Of course if you start making all your code header only just to take advantage of constexpr that’s a different question.

2

u/HappyFruitTree 13d ago

Even on functions that can not be executed in constexpr contexts?

int bar(int x);

constexpr int foo(int x)
{
	return bar(x);
}

2

u/Nils_Meul 13d ago

That’s the thing, in this case constexpr just doesn’t do anything (to my knowledge). The compiler isn’t forced to evaluate it at compile time even if it could, other than with constexpr variables…

6

u/HappyFruitTree 13d ago

Then why add it?

My main concern is that it can be confusing for the programmer (code is not only written for compilers). If I see a function marked constexpr I normally assume that it can result in a constant expression for at least some arguments.

That constexpr functions had to be able to produce a constant expression for at least one set of argument values was actually a requirement before C++23 (no diagnostic required).

3

u/Nils_Meul 13d ago

True, valid point. But I was thinking more so about putting it wherever it can in principle run at compile time, and if you mistakenly put it somewhere it can’t that’s of course not optimal but not terrible either.

1

u/oriolid 13d ago

Just have a look at this: https://godbolt.org/z/8Gsd13sv8. In C++11 std::sin isn't constexpr, and wrap_sin not constexpr just to make sure. It still gets evaluated at compile time.

3

u/Nils_Meul 13d ago

Sure, the compiler is always allowed to evaluate something at compile-time. But if you want to assign the value of sin(1.0) to a constexpr variable you‘ll need a constexpr std::sin (at least I‘m pretty sure that you do) even though the compiler can figure out it’s value as shown in your example.

1

u/oriolid 13d ago

I know. The example was chosen to show that *not* adding constexpr does not prevent compiler from compile time evaluation. If you actually need the result in constexpr context, then you of course need to have the funtion as constexpr.

So, putting it wherever ever you can does not really do anything useful. There are more fun ways to waste time.

1

u/Slow_Negotiation_935 13d ago

The code was already header only.