Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C can you define a constant based on another constant?

Tags:

c

constants

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;
like image 391
Hunterfang Avatar asked Mar 23 '17 00:03

Hunterfang


1 Answers

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.

like image 106
M.M Avatar answered Oct 28 '22 14:10

M.M