What is the difference between constexpr int *np = nullptr
and int const *np = nullptr
?
np
is a constant pointer to an int that is null, in both cases. Is there any specific use of constexpr
in context of pointers.
constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time. A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations.
constexpr creates a compile-time constant; const simply means that value cannot be changed.
If you try to do anything with the pointer and use the result in a constant expression, then the pointer must be marked as constexpr. The simple example is pointer arithmetic, or pointer dereferencing:
static constexpr int arr[] = {1,2,3,4,5,6};
constexpr const int *first = arr;
constexpr const int *second = first + 1; // would fail if first wasn't constexpr
constexpr int i = *second;
In the above example, second
can only be constexpr
if first
is. Similarly *second
can only be a constant expression if second
is constexpr
If you try to call a constexpr
member function through a pointer and use the result as a constant expression, the pointer you call it through must itself be a constant expression
struct S {
constexpr int f() const { return 1; }
};
int main() {
static constexpr S s{};
const S *sp = &s;
constexpr int i = sp->f(); // error: sp not a constant expression
}
If we instead say
constexpr const S *sp = &s;
then the above works works. Please note that the above does (incorrectly) compiled and run with gcc-4.9, but not gcc-5.1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With