tags:

views:

321

answers:

4

I would like to use some previously defined constants in the definition of a new constant, but my C compiler doesn't like it:

const int a = 1;
const int b = 2;
const int c = a;         // error: initializer element is not constant
const int sum = (a + b); // error: initializer element is not constant

Is there a way to define a constant using the values of other constants? If not, what is the reason for this behavior?

+2  A: 

You can only assign a literal to a const variable, so that program is illegal. I think you should go with the preprocessor.

akappa
+7  A: 

Const vars can't be defined as an expression.

#define A (1)
#define B (2)
#define C (A + B)

const int a = A;
const int b = B;
const int c = C;
phillc
Preprocessor... Yuck, but you gotta go with what works
BCS
#undef A #undef B #undef C
Steve Jessop
+6  A: 

Use enums in preference to preprocessor macros for integral const values:

enum {
    A = 1,
    B = 2
};

const int a = A;
const int b = B;
const int c = A;        
const int sum = (A + B);

Works in C and C++.

Michael Burr
wouldn't making the all vars "static const int" and such work as well?
Evan Teran
Not for C, only for C++ - but in that case you don't need the 'static' just being a previously seen const int is enough to make the identifier useable as part of an initializer for a const (or array size).
Michael Burr
+1  A: 

Since the results are meant to be constant, I agree with Michael Burr that enums are the way to do it, but unless you need to pass pointers to constant integers around, I wouldn't use the 'variables' (is a constant really a variable?) but just the enums:

enum { a = 1 };
enum { b = 2 };
enum { c = a };
enum { sum = a + b };
Jonathan Leffler
I would agree, but I was a bit lazy and didn't want to get into the whole modifyable vs. non-modifyable lvalue thing. Another little wrinkle is that with enums you have less control over the types, which may matter in terms of overload selection (obviously a C++ issue only). However, these 2 things are very much rare corner cases - 99.9% of the time using enums alone as the 'manifest constant' works great. And you avoid pretty much all the problems inherent in preprocessor macros.
Michael Burr