Why can function pointers be `constexpr`?

前端 未结 4 2043
花落未央
花落未央 2021-02-03 22:31

How does the compiler know where in memory the square root will be before the program is executed? I thought the address would be different everytime the program is executed, bu

4条回答
  •  孤独总比滥情好
    2021-02-03 23:16

    Address value is assigned by a linker, so the compiler does not know the exact address value.

    cout << fp(5.0); 
    

    This works because it is evaluated at run-time after exact address has been resolved.

    In general, you cannot use the actual value (address) of constexpr pointer because it is not known at compile-time.

    Bjarne Stroustrup's C++ Programming language 4th edition mentions:

    10.4.5 Address Constant Expressions

    The address of a statically allocated object (§6.4.2), such as a global variable, is a constant. However, its value is assigned by the linker, rather than the compiler, so the compiler cannot know the value of such an address constant. That limits the range of constant expressions of pointer and reference type. For example:

       constexpr const char∗ p1 = "asdf";
       constexpr const char∗ p2 = p1;     // OK 
       constexpr const char∗ p2 = p1+2;   // error : the compiler does not know the value of p1 
       constexpr char c = p1[2];          // OK, c==’d’; the compiler knows the value pointed to by p1
    

提交回复
热议问题