Today while I was developing a C program a college of mine pointed out that I was doing something wrong.
He said that the code that I was doing which is similar to the code below is wrong, and that you can't define a constant based on another constant. The program ended up working anyway, and I was left wondering if he was right. Is the code below wrong/breaks best practices?
const int num=5;
const int num2=num*2;
These are not constants; they are int
variables with a const
qualifier. The const
qualifier means that the variable cannot be written to by the program. Examples of actual integer constant expressions include 5
, 2 + 3
, and sizeof(int)
. Here is a full list.
At file scope the second line is a constraint violation, because the name of a variable is not a constant expression. The constraint is C11 6.7.9/4:
All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.
(variables declared at file scope have static or thread storage duration).
At block scope the code is OK, because initializers do not need to be constant expressions there.
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