Const in C

This code does not compile:

const int x = 123; const int y = x; 

He complains that the "initialization element is not constant" for the string y =. Basically I want to have two const values, one of which is defined in terms of the other. Is there a way to do this in C or do I need to use unsafe type #defines or just write the values โ€‹โ€‹literally as magic numbers?

+4
source share
6 answers

When assigning a type to const, you can only assign literals, for example: 1, 2, 'a', 'b', etc., and not variables such as int x, float y, const int z, etc. Variables, even though your variable is really not a variable (since it cannot change) is not acceptable. Instead, you need to do:

 const int x = 123; const int y = 123; 

or

 #define x 123 const int y = 123; 

The second one works because the compiler will be broken wherever x is, and replace it with a literal before compiling it.

+8
source

You can use enum to achieve this:

 enum { x = 123, y = x }; 
In this case, typed

( x and y ).

+3
source

c only supports literals or other elements that are known at compilation that are immutable.

+1
source

C only supports literals as constant initializers. You cannot initialize const with a variable.

But C supports

 #define x 100 const int y = x; 
0
source

C only supports literals as constant initializers. Thus, you will need to use some value to initialize your const, you cannot do this in terms of other variables that are constants themselves.

However, this raises another important issue. The "const" value of a variable is known to the compiler when compiling, so why is this construction not allowed? ... Can any of the C experts comment on this?

0
source

Your y not a constant in the understanding of C, but a variable called const .

The expressions for the compile time constant that you want to use may contain:

  • literals
  • enum constants
  • sizeof expressions
  • address expressions related to functions
  • address expressions related to objects with static storage duration

and can combine them mainly with ordinary arithmetic if the resulting type is compatible with the type of the left side.

0
source

All Articles