Reputation: 1536
I understand how each works, but I was curious if one or the other actually is more efficient memory-wise. #define seems to be used all the time in the embedded C world, but I am wondering if it is actually justified over a const most of the time.
If one is more efficient than the other, does anyone have some way to test and show this?
Upvotes: 3
Views: 5702
Reputation: 1963
It depends on whether you are taking the address of the constant or not. If you do not take the address of the constant, then the compiler has no problem folding it into other computations and emitting it inline (as an immediate or literal), just like the #define
d version. However, if you write:
const int c = 42;
const int *pc = &c;
then a copy of c
must live in the global .rodata
section in order to have its address taken, adding sizeof(int)
bytes of Flash space atop any copies the compiler decided to inline; however, the compiler might be able to fetch that constant from memory more cheaply than it can incorporate it as an inline literal, depending on its value and what CPU you're compiling for.
Try compiling some code each way and looking at the resulting assembler listings...
Upvotes: 5
Reputation: 385114
Let's put #define
aside, because it doesn't really exist in your program. The preprocessor takes your macros and expands them before the compiler can even spot that they were ever there.
The following source:
#define X 42
printf("%d", X);
is actually the following program:
printf("%d", 42);
So what you're asking is whether that takes more or less memory than:
const int x = 42;
printf("%d", x);
And this is a question we can't fully answer in general.
On the one hand, the value 42
needs to live in your program somewhere, otherwise the computer executing it won't know what to do.
On the other hand, it can either live hardcoded in your program, having been optimised out, or it can be installed into memory at runtime them pulled out again.
Either way, it takes 32 bits (it may not be 32) and it doesn't really matter how you introduced it into your program.
Any further analysis depends on precisely what you are doing with the value.
Upvotes: 6