c++: constexpr function doesn't evaluate at compile time when using with std::cout

Ojs*_*Ojs 6 c++ c++14

I'm new with c++ and currently came across with constexpr. As I realize constexpr functions are evaluated at compile time. Here is my source code:

constexpr int sum(float a, int b)
{
    return a + b;
};

int main(int argc, char *argv[])
{
    std::cout << sum(1, 2) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

It is a simple function which just sums to integers. The problem is that when I set breakpoint at return a + b and start debugging, the breakpoint is hit, which means that the function was not evaluated at compile time. But when I change main function to this:

int main(int argc, char *argv[])
{
    constexpr int var = sum(2, 2);
    std::cout << var << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

the breakpoint is not hit, which means that function was evaluated at compile time. I'm little confused why function is not evaluated in first case?

P.S I'm using visual studio 2017.

Vit*_*meo 13

As I realize constexpr functions are evaluated at compile time

Not really. They can be evaluated at compile-time, but they are not guaranteed to do so, unless they're invoked in a context where a constant expression is required.

One such context is the declaration of a constexpr variable.

  • @NorbertLange呃,您可以为此指定标准报价吗? (2认同)

for*_*818 7

constexpr表示“可以在编译时评估”,而不是“必须在编译时评估”。如果要在编译时评估它,可以在需要在编译时评估的上下文中调用它,例如模板参数:

std::array<int, sum(3,5)> x;
Run Code Online (Sandbox Code Playgroud)

请注意,动机constexpr是与许多人所期望的相反。constexpr告诉编译器您可以使用它,例如作为模板参数,如果sum不是,constexpr则会出现编译器错误。不能确保始终在编译时评估函数。