Quick Q: Why can a constexpr function return a non-constant?

Quick A: Because constexpr means can be evaluated at compile time, not that it will be. And it won’t be if the inputs aren’t compile-time constants.

Recently on SO:

I am confused about a constexpr function?

In C++ Primer, Fifth Edition, §6.5.2:

A constexpr function is defined like any other function but must meet certain restrictions: The return type and the type of each parameter in must be a literal type (§2.4.4, p. 66), and the function body must contain exactly one return statement

but another sentence in this chapter (page 239):

A constexpr function is permitted to return a value that is not a constant

// scale(arg) is a constant expression if arg is a constant expression
constexpr size_t scale(size_t cnt) { return new_sz() * cnt; }

Is it a contradictory summary? I am confused about it.
The return type of scale is literal type?
update: what's the difference between literal type and constant ?

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.