gdoug
gdoug

Reputation: 775

Most RAM efficient way to reference integer constants in C

I am working on a application for micro-controller/sensor devices. My question is, what is the most memory efficient way to store named constants in such a way they can be referenced from other locations? Ideally, we would want to avoid storing the same value in either RAM/ROM over and over again. The obvious choices are

  1. #define CONSTANT 0
  2. extern int CONSTANT = 0;
  3. const int CONSTANT = 0;
  4. (Some mix of 3. and 4.)
  5. enum ... (for multiple constants)

Again, I want to prevent storing these values over and over again in memory. So if I have

if (CONSTANT == x)
{
    ...
}
...
y = CONSTANT;

the goal would be to prevent CONSTANT being stored twice. Perhaps this is a compiler optimization issue, or what I am thinking is not possible since you would end up having to store a pointer and reading from it, making it less efficient than storing multiple copies in the first place.

Upvotes: 1

Views: 204

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320551

As you noted yourself, storing an integer constant in data region of memory provides no memory savings when the size of the constant is smaller or equal to the size of memory address. This is because any machine instruction that refers to that stored constant will have to store its address. Size of int objects is usually smaller or equal to the size of machine address. For this reason, for int constants it makes more sense to embed them directly into machine instructions instead of storing them in data region.

If we interpret the specification of C language in the most literal way, that would mean that you'll have to use #define or enum - only these C language constructs can formally produce true constants. Of course, nothing prevents a C compiler to optimize the code and treat [static] const int objects as true constants as well, even though they are not recognized as such by the formal definition of the language. You have to test your compiler and see if it does that or not.

An extern const int object declared in some translation unit without an initializer cannot be embedded into machine instructions in that translation unit, which means that extern const int will not work well for this purpose (unless your compiler is capable of global optimizations).

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308216

For both #define and enum the compiler will be able to code the integer constant into the generated instructions. It may also be able to do it with const int but that depends on the optimization capabilities of your compiler. The extern will almost always need to reference an address, which means the value will be somewhere else taking up memory.

Yes, the constant will be stored more than once, but that's preferable to a pointer to the constant being stored more than once.

Upvotes: 1

Related Questions