-5

Is it wasting memory to have something like

static const char size = sizeof(struct MyStruct);

If they are evaluated at compile time, that is like doing;

static const char size = 10;
functioncall(size);
functioncall2(size);

Which is more optimal:

#define STRUCTSIZE sizeof(struct MyStruct)

or

static const char size = sizeof(struct MyStruct);

This allocates extra memory at runtime for a value that's constant, if sizeof is evaluated at compile time. If it is evaluated at compile time, I might as well use a macro for memory efficiency. However, if they are evaluated at runtime, this variable would save processing power as it would not have to evaluate it over and over as I use it. So. Are sizeof statements evaluated at compile time or runtime?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93

1 Answers1

3

In C, are sizeof() statements evaluated at compile time or runtime?

Usually yes. However, when applied to a variable length array, it is evaluated at runtime. Otherwise the operand expression is not evaluated at all, and only the type of the expression is used to determine the result.

There is no advantage to using a macro in place of the variable in this case. Note that using the variable is not necessary either and may obfuscate the program. This is mostly a matter of style however.

eerorika
  • 232,697
  • 12
  • 197
  • 326