Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a compiler get a const's address in C++?

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);
}
like image 556
imsrch Avatar asked Apr 07 '13 13:04

imsrch


People also ask

How does the const keyword work in C?

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.

Does constant have address?

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.

How to declare const variable in c++?

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 .

What does const function mean in c++?

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.


2 Answers

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.

like image 64
Alok Save Avatar answered Sep 24 '22 21:09

Alok Save


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.

like image 43
Some programmer dude Avatar answered Sep 20 '22 21:09

Some programmer dude