Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of global const definition

Tags:

c++

c

I suppose this question was already asked but I couldn't find it. If I use macros instead of constants like this:

 #define A 0
 #define B (A+1)
 #define C (B+A)

then it's guaranteed to be defined in strict order (A then B then C). But what would happen if I use consts instead?

 const int A = 0;
 const int B = A + 1;
 const int C = A + B;

If that's in function scope - it's fine. But what about global scope? As far as I know, order of definition of global variables is not guaranteed. And what about consts?

I think that is the last thing that stops me from using consts instead of macros.

(I'm also curious if there are any differences between C and C++ in this particular matter).

UPD: The question should be like this: what are the differences (if any) between C and C++ in this matter?

like image 649
Amomum Avatar asked Nov 11 '13 10:11

Amomum


3 Answers

Per §3.6.2/2 in the standard:

Variables with ordered initialization defined within a single translation unit shall be initialized in the order of their definitions in the translation unit.

So your code is well-formed and has one result in any standard C++ compiler.

like image 51
masoud Avatar answered Oct 06 '22 00:10

masoud


Your code will work well as long as your 3 lines are in the same source file. (in C++). In C you'll get an error.

like image 20
Rémi Avatar answered Oct 06 '22 01:10

Rémi


Defining and initializing in this way at global scope is guaranteed to result in compile time error (in C):

error: initializer element is not constant
like image 33
David Ranieri Avatar answered Oct 06 '22 00:10

David Ranieri