Is there a way to use constant variables in the definitions of other constants?

I would like to use some previously defined constants in the definition of the new constant, but he does not like my C compiler:

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?

+3
source share
4 answers

Const vars cannot 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;
+7
source

Use enumerations, preferring preprocessor macros for integral constant values:

enum {
    A = 1,
    B = 2
};

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

It works in C and C ++.

+7
source

, . , .

+2

Since the results must be constant, I agree with Michael Burr that enumerations are a way to do this, but if you do not need to pass pointers to constant integers, I would not use "variables" (is this constant really a variable?), But just enums :

enum { a = 1 };
enum { b = 2 };
enum { c = a };
enum { sum = a + b };
+2
source

Source: https://habr.com/ru/post/1707208/


All Articles