yadhu
yadhu

Reputation: 1333

constexpr concept in c++11

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?

Upvotes: 3

Views: 269

Answers (3)

Bayleef
Bayleef

Reputation: 195

The compiler then assembler generates the machine code and the addresses of variables. The addresses could be absolute or they could be relocatable. The addresses then must be fixed when the loader puts them into segments of memory or while they are in memory. All constexpr says is that you can evaluate these things at compile time and yes you can. There is an address. There is a value. The machine code or executable code will literally be updated in the background with addresses based on new offsets by the operating system. The programmer is no longer worried about absolute addressing on 16 bit real systems. The programmer only has to know how the process works really.

Arrays are contiguous in memory so therefore even with relative addressing the distance in between will be N bytes ....A very constant expression indeed lol

Upvotes: 0

Mike van Dyke
Mike van Dyke

Reputation: 2868

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.

Upvotes: 10

P.W
P.W

Reputation: 26800

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.

Upvotes: 2

Related Questions