5

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?

Amomum
  • 6,217
  • 8
  • 34
  • 62
  • Please ask only one question per Question. In this case, you should pick one of: What does C specify about this? What does C++ specify about this? What are the differences between C and C++ about this? As you can see, you are already getting some Answers that answer one of these questions but not others. This makes it difficult to vote for them and to choose one as accepted. You may enter multiple separate Questions. – Eric Postpischil Nov 11 '13 at 12:38
  • @EricPostpischil i suppose, the third question is the most complete. Thank you. – Amomum Nov 12 '13 at 10:41

4 Answers4

6

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.

Lundin
  • 195,001
  • 40
  • 254
  • 396
masoud
  • 55,379
  • 16
  • 141
  • 208
3

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.

Rémi
  • 3,705
  • 1
  • 28
  • 39
  • 3
    Can you please give me a quote from a standart? – Amomum Nov 11 '13 at 10:58
  • http://stackoverflow.com/a/10011133/480529 "Objects defined within a single translation unit and with ordered initialization shall be initialized in the order of their definitions in the translation unit." seems to be relevant – Rémi Nov 11 '13 at 11:12
2

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
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
0

In C this is an error, this is because the const variables are allocated memory by c compiler.

In C++ compiler is free to embed the const variable in the code. Hence C++ wont throw any error. constvariables are allocated memory only if you use address of (&) operator with them.

Hence your code will work in C++ if the 3 lines are in that order. In C, compiler will throw an error, because of the fact that initializing a const can not be done using variable!!!