As is discussed here Which memory area is a const object in in C++?, a compiler will probably not allocate any storage for the constants when compiling the code, they may probable be embedded directly into the machine code. Then how does a compiler get a constant's address?
C++ code:
void f()
{
const int a = 99;
const int *p = &a;
printf("constant's value: %d\n", *p);
}
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. In C, constant values default to external linkage, so they can appear only in source files.
A constant may not have an address at all. And even if a constant value is stored in memory at runtime, this is to help the runtime to keep constants that: constant.
To declare a constant variable in C++, the keyword const is written before the variable's data type. Constant variables can be declared for any data types, such as int , double , char , or string .
Const member functions in C++ The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided.
Whether a constant will be allocated any storage or not is completely dependent on the compiler. Compilers are allowed to perform optimizations as per the As-If rule, as long as the observable behavior of the program doesn't change the compiler may allocate storage for a
or may not. Note that these optimizations are not demanded but allowed by the standard.
Obviously, when you take the address of this const
the compiler will have to return you a address by which you can refer a
so it will have to place a
in memory or atleast pretend it does so.
All variables must be addressable. The compiler may optimize out constant variables, but in a case like your where you use the variable address it can't do it.
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