Reputation: 71
sorry if this question seems naive, but I haven't been able to find a clear answer to it anywhere. I must define a constant in terms of previously defined constants, like
#define CONST_A 2
#define CONST_B 3
#define CONST_C CONST_A*CONST_B
The actual values of CONST_A
and CONST_B
are fed as defineflags to gcc, so I can't just write #define CONST_C 6
.
If I understand correctly, this will tell the preprocessor to replace any appearance of CONST_C
by 2*3
and not 6
, right? I'm mainly worried about performance, so I would prefer the latter. I'm guessing this could be done by using static const
instead of preprocessor #define
. Is this the best option?
Thanks in advance!
Upvotes: 3
Views: 496
Reputation: 145829
C say that constant expressions can be evaluated at compile time and any today's decent compiler will evaluate constant expressions at compile time. This compiler operation is known as constant folding.
(C99, 6.6p2) "A constant expression can be evaluated during translation rather than runtime, and accordingly may be used in any place that a constant may be."
Upvotes: 0
Reputation: 154911
Don't worry about performance of constant expressions like 2 * 3
in C. C compilers have been able to eliminate such expressions by evaluating them at compile-time for at least 20 years.
static const
can be preferred for other reasons, such as type-safety or not having to worry about precedence (think what happens if CONST_A
is defined as 2+2
), but not for performance reasons.
Upvotes: 9