Does the constant use more or less memory than the usual #define?

I understand how things work, but I was curious if one or the other is actually more memory efficient. #define seems to be used all the time in the embedded C world, but I'm wondering if this is actually warranted for most of the const.

If one is more efficient than another, does anyone have a way to test and show this?

+3


source to share


2 answers


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 notice that they ever were.

Next source:

#define X 42
printf("%d", X);

      

is actually the following program:

printf("%d", 42);

      

So what you are asking is what takes up more or less memory than:



const int x = 42;
printf("%d", x);

      

And this is a question that we cannot fully answer as a whole.

On the one hand, the value has 42

to be somewhere in your program, otherwise the computer running it won't know what to do.

On the other hand, it can either live hardcoded in your program, or has been optimized, or it can be set to memory at runtime, which they pulled again.

It takes 32 bits anyway (maybe not 32) and it doesn't really matter how you put it into your program.

Any further analysis depends on what you are doing with the value.

+4


source


It depends on whether you accept a constant address or not. If you don't take the address of the constant, then the compiler has no problem folding it into other computations and emitting it inline (as immediate or literal) like version #define

d. However, if you write:

const int c = 42;
const int *pc = &c;

      



then the copy c

must be in the global section .rodata

in order to have its own address, adding sizeof(int)

bytes of Flash space to all copies that the compiler decided to embed; however, the compiler may be able to extract this constant from memory more cheaply than it may include it as an inline literal, depending on its meaning and which processor you are compiling for.

Try compiling some code anyway and looking at the resulting assembler lists ...

+3


source







All Articles