Originally Posted by
@nthony
Practically, I know it should not matter, but it is of much interest to me how the memory management works on a machine code level (i.e. assembley). It would be of great help if someone could clarify exactly what happens on a assembler level when a const is used vs a #define.
You should learn assembly if you really want an understanding of C's memory handling, but here it goes.
The following assembly is more or less pseudocode. I haven't done any actual assembly in years.
-------------------------------------------------
First, an introduction to my assembly pseudocode...
The data segment contains information which is included in the exe and is loaded into memory when the program is run. It can be roughly though of as 'global' memory.
The code segment contains information which is included in the exe and is loaded into memory when the program is run. It is the machine code of the program.
The assembly is very simplified, and I made up the directives and instructions on the fly. Everything after a ';' is meant to be a comment.
db stands for 'declare byte'. 'dlw' stands for 'declare long word', or 32 bits.
Inline code.
Code:
int main (void) {
printf("%d\n", 3);
return 0;
}
Translates into something like this:
Code:
segment data
__string1:
db '%d\n\0' ; 4 bytes are allocated in the data segment
segment code
__main:
push 3
push __string1
call printf
ret 0
-----------------------------
The equivalent 'const' code.
Code:
int const i = 3;
int main (void) {
printf("%d\n", i);
return 0;
}
Code:
segment data
__string1:
db '%d\n\0' ; 4 bytes are allocated in the data segment.
i:
dlw 3 ; I assume 'int' is a 32-bit value, so 4 more bytes.
segment code
__main:
push lookup i ; Note that i is an address value. So, at the machine level,
; a very basic sort of dereferencing has to happen. Processors, of course,
; are very much optomized for this kind of operation.
push __string1
call printf
ret 0
So, the inlined code should take up less space in memory, and as a file, because of the smaller data segment.
----------------------------------------------
Before anyone claims that the C compiler will just turn the const code into equivalent #define code, I would like to point out that const and #define are not equivalent. Const neccisarily needs store the variable somewhere in memory so we can do things like this:
Code:
int const i = 3;
int main (void) {
int const * p = &i;
printf ("%d\n", *p);
return 0;
}