Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const values in C

Tags:

c

constants

This code doesn't compile:

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

It complains that "initializer element is not constant" for the y= line. Basically I want to have two const values, one defined in terms of the other. Is there a way to do this in C or do I have to use type-unsafe #defines or just write out the values literally as magic numbers?

like image 732
Shum Avatar asked Dec 17 '22 14:12

Shum


1 Answers

When assigning const type you can only assign literals i.e.: 1, 2, 'a', 'b', etc. not variables like int x, float y, const int z, etc. Variables, despite the fact that your variable is really not variable (as it cannot change) is not acceptable. Instead you have 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 strip everywhere there is x and replace it with a literal before it is compiled.

like image 54
Dair Avatar answered Dec 23 '22 17:12

Dair