Const int doesn't take a space?

In a comment on answer using anonymous enum , Oli Charlesworth states that:

const int is immutable and may not take up any space, depending on what the compiler chooses.

If I declare const int i = 10 , how is it stored 10 if it "cannot take any place"?

Assuming int is 4 bytes, I would suggest that at least 4 bytes are reserved for storing 10 as const int .

+8
c memory int
Aug 22 '11 at 13:14
source share
7 answers

The compiler can optimize the code as it sees fit, until the resulting code has the same observed side effects.

Thus, variables can be optimized to exist only in registers or replaced with immediate values. In pseudo-machine code:

 SET 10, eax ST eax, &i # Initialise i ... LD &i, eax # Add i to ebx ADD eax, ebx, ebx 

can be:

 SET 10, eax ADD eax, ebx, ebx 

or even just:

 ADD 10, ebx, ebx 
+9
Aug 22 2018-11-18T00:
source share

If you do not use i in such a way that an address is required, the compiler usually just uses it at compile time, and at runtime all that remains is 10 , not a variable.

In particular, since a const does not change, there is no need to store it in memory unless you do something like passing it to a function that takes a parameter by reference.

+6
Aug 22 2018-11-21T00:
source share

Well, it’s a little wrong to say that it will take up no space, since the course value will still remain in the command space in memory, but space will not be assigned to store the variable as the data type in question. Perhaps it would be more appropriate to say that the minimum amount of memory, which, in my opinion, is what your reaction indicates.

+4
Aug 22 '11 at 13:27
source share

The compiler can replace the number 10 every time it needs to read i instead of reading the stored value.

+3
Aug 22 2018-11-21T00:
source share

It can be part of the code and used as a constant immediate value (for example, #define FIVE 5 ), for example.

+2
Aug 22 2018-11-18T00:
source share

The compiler can simply replace all occurrences of i in your code with a constant of 10. There is no i anymore, therefore there is no space requirement, it costs the same (if the compiler is not simple dumb or sees that you are casting out the const) using magic numbers, just makes for much more readable code. With small constants, it can reset them in the assembly instructions.

+2
Aug 22 2018-11-21T00:
source share

Most likely, this will take place if you declare it in the global namespace. If you declare it in the function body or declare it β€œstatic”, the compiler can remove it. If you declare it globally, the compiler does not know if the constant refers to another translation unit.

0
Aug 22 2018-11-18T00:
source share



All Articles