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?
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.
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.
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
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