c++pointersconstexprconstexpr-function

How do `constexpr` "compile time pointers" work in C++?


Background

Pointers cannot be used as T* p value parameters to a template (which is specialized at compile time), because the memory address &obj of some object T obj is only known at run time.

Question

If that background is correct, than how can a pointer be used at compile time instead of this being ill-formated:

constexpr size_t length(const char* str)
{
    size_t n = 0;
    while (str[n] != '\0')
    {
        n++;
    }
    return n;
}


//...

constexpr size_t length = length("Monkey types Hamlet!");

What memory is str actually pointing to at compile time?


Solution

  • constexpr T obj = /* something */;
    

    this expression requires that something is a constant expression, there is no difference between a pointer and a value, so long as the pointer and the object pointed to are constant expressions, therefore the following code is valid https://godbolt.org/z/eaT77cvjP

    constexpr int value = 5;
    constexpr const int* ptr = &value;
    
    constexpr int add_one_ptr(const int* value)
    {
        return *value + 1;
    }
    constexpr int add_one_value(int val)
    {
        return val + 1;
    }
    
    constexpr int value1 = add_one_value(value);
    constexpr int value2 = add_one_ptr(ptr);
    constexpr int value3 = add_one_ptr(&value);
    

    in case of C string literals, they are implicitly constexpr const char*