I was going to through the concepts of constexpr in C++. My understanding of is that constexpr gets evaluated at compile time. In here, I found an example where they have following snippet.
int z[30];
constexpr auto e2 = &z[20] - &z[3];
They are calculating the difference between the addresses at compile time. How can that be evaluated at compile time when we don't know that actual values of addresses at compile time?
constexpr auto e2 = &z[20] - &z[3];
just calculates the offset between the third and the 20th element. So there's no need to know the adresses.
On the other hand the following example does not work, because the addresses of z[20] and t are evaluated at runtime.
int z[30];
int t;
constexpr auto e2 = &z[20] - &t;
As pointed out by Passer By this is undefined behaviour according to the standard (7.6.6 Additive operators, last sentence):
Unless both pointers point to elements of the same array object, or one past the last element of the array object, the behavior is undefined.
The compiler does not need to know the actual values of the addresses. It employs simple pointer arithmetic. Since z is an array of integers, subtracting two addresses of integers in an array will yield the difference between the subscripts.
So
constexpr auto e2 = &z[20] - &z[3];
will result in the value of 17 being assigned to e2.
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