Alex Rivera | Logout

How much memory does a constant take in C?

Asked 2009-11-03T16:23:34.150
13

when doing like this:

const int a = 5;

I wonder if a will get 4-byte of memory just like a variable ? (in 32 bit system)

Edit
Report

3 Answers

4

It depends.

const int a = 5;

Will take four bytes of memory (or however many bytes an int takes up on your system).

If you make it static:

static const int a = 5;

Then the optimizer is free to replace each instance of a with the value of 5. The optimizer cannot do that in the first (non-static) case simply because you may refer to a in a separate compilation unit with:

extern const int a;
answered 2009-11-03T16:35:45.217
1

It depends on your architecture but yes whether you make something const or not does not really affect its size but more its location in memory. Now, there are some compiler optimizations that may change what you think will actually happen but this is the basic idea.

answered 2009-11-03T16:25:01.543
1

a constant variable requires 4 bytes of memory, but if it is a value it requires 0 bytes since the assembly code will embbed the value like this

mov eax, 5

here 5 don“t comes from a variable but it is the constant 5, and it will even generate faster code since no memory call are required to retrieve the value, it is just part of the assembly code

answered 2009-11-24T22:24:11.670

Your Answer