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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With