0

Can we initialize a const variable as follows

int var1 = 10;
const int var2 = var1;

Will this cause any warning/error in any compiler ?

3
  • 3
    Is it really called a const variable? That feels like an oxymoron. Commented Jun 18, 2011 at 13:24
  • @David: There is no notion of "variable" in either C or C++ standards. The technical term is "const object", I think. Commented Jun 18, 2011 at 13:27
  • 3
    @Armen: in fact C++ does contain a notion of a "variable", 3/4: "A variable is introduced by the declaration of an object. The variable's name denotes the object". So a variable is a named object, regardless of whether it's const or not. Or, if we want to get all Goedel-Escher-Bach, the variable isn't explicitly stated to be the object, but it is a thing that has the same name as the object does! The C99 standard uses the noun "variable" in notes, apparently with a similar meaning. Commented Jun 18, 2011 at 13:33

2 Answers 2

14

Depends where the code is.

If it's inside a function, so that var1 and var2 are automatics, then yes this is fine. var2 is only initialized by copying var1 anyway, so the fact that var1 can be modified later has no bearing on the fact that var2 can't.

If it's in file scope, so that var1 and var2 are statics, then no it is not fine. A const integer object at file scope must be initialized with a value certain to be known at compile time (in C++ this is called an "integer constant expression", I forget whether that's the exact C terminology too). In this case, you might think that because there's no code in between the two definitions, the value of var1 would be known at compile time to be 10, but because the type is non-const, the standard forbids it anyway. You can think of this as being in order to avoid implementations needing to be smart enough to apply that line of reasoning and prove that there's nothing capable of modifying var1: all it has to look at is the type, not the intervening code.

Sign up to request clarification or add additional context in comments.

Comments

1

Yes, it's OK. It's part of C and C++ standards. A constant object can be initialized with a non-const object. Why wouldn't it?

1 Comment

Hmm... downvote? Can you please provide a quote from the standard which says this isn't OK? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.