What is constexpr in C++?

前端 未结 4 2229
不思量自难忘°
不思量自难忘° 2021-02-07 07:48

I am really confused about a constexpr concept, as I have read constexpr is evaluated at compile time, so it is useful for performance optimization ver

4条回答
  •  时光取名叫无心
    2021-02-07 08:23

    As you said, constexpr is evaluated at compile time. So the value must be evaluable when compiling.

    For example:

    constexpr int i = 0;
    constexpr int& ri = i;
    

    For first line, 0 is evaluable when compiling, its value is 0.

    But for second line, compiler needs address of i to do the assignment, which is determined at runtime. So this line will fail.

提交回复
热议问题