I was going through the topics of constexpr and consteval and found the below,
- We can have pointers that are of type CONSTEXPR
- A CONSTEVAL function can return a pointer of a CONSTEXPR variable
and my question here is that, how is the above 2 possible?
The above 2 questions because, as far as I am aware, all the variables are created in the memory during runtime and pointer is the address of that memory.
So, how can pointer of type CONSTEXPR exist (since CONSTEXPR variables have to be initialized at compile time)? and how can a CONSTEVAL function return a pointer of CONSTEXPR variable during the compile time?
#include <iostream>
constexpr int a{1};
consteval const int* aptrfunc() //How can this function return a pointer at compile time
{
return &a;
}
int main()
{
constexpr const int* aptr{&a}; //How can this exist at compiletime?
std::cout<<aptr<<'\n'; //Prints address of a
std::cout<<aptrfunc()<<'\n'; //Prints address of a
return 0;
}
Yes but not all of them have a fixed address.
As far as the standard is concerned, a constexpr pointer is allowed to point to an object that remains at a fixed address. And an object defined outside any function(global object) have a fixed address and so it's address can be used to initialize a constexpr pointer.
As in your example,
a
is a globalint
and hence remains at fixed address, so a constexpr pointer can be made to point to it.An implementation/compiler might deal with such(constexpr) pointers symbolically but that is an implementation detail.