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;
}
constexpr-ness isn't a part of the type, it's a separate property of a variable (or function or something else).constexprpointer can point to it.constexprobjects havestaticstorage class, meaning they have static duration. That is, their address is determined at compile-time. Beforecostexperkeyword, having to waste cpu cycles at run-time for such information that is available at compile-time was really annoying. If only you had experience with assembler, you'd know there's a.datasection or something.