Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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;
}

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;
}

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.

like image 852
Ojs Avatar asked Apr 26 '19 11:04

Ojs


People also ask

Is constexpr evaluated at compile time?

A constexpr function that is eligible to be evaluated at compile-time will only be evaluated at compile-time if the return value is used where a constant expression is required. Otherwise, compile-time evaluation is not guaranteed.

Is constexpr guaranteed?

Quick A: constexpr guarantees compile-time evaluation is possible if operating on a compile-time value, and that compile-time evaluation will happen if a compile-time result is needed.

What is constexpr in C ++ 11?

The keyword constexpr was introduced in C++11 and improved in C++14. It means constant expression. Like const , it can be applied to variables: A compiler error is raised when any code attempts to modify the value. Unlike const , constexpr can also be applied to functions and class constructors.


2 Answers

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.

like image 85
Vittorio Romeo Avatar answered Nov 15 '22 22:11

Vittorio Romeo


constexpr means "can be evaluated at compile time" rather than "must be evaluated at compile time". If you want to see it evaluated at compile time you can call it in a context that requires to be evaluated at compile time, for example a template parameter:

std::array<int, sum(3,5)> x;

Note that the motivation for constexpr is the other way around than many would expect. constexpr tells the compiler that you can use it eg as template parameter and if sum was not constexpr you'd get a compiler error. It is not to make sure that the function always is evaluated at compile time.

like image 27
463035818_is_not_a_number Avatar answered Nov 15 '22 23:11

463035818_is_not_a_number