views:

231

answers:

4

Can I mix extern and const, as extern const? If yes, does the const qualifier impose it's reign only within the scope it's declared in or should it exactly match the declaration of the translational unit it's declared in? I.e. can I declare say extern const int i; even when the actual i is not a const and vice versa?

A: 

Yes, you can use them together.

If you declare "extern const int i", then i is const over its full scope. It is impossible to redefine it as non-const. Of course you can bypass the const flag by casting it away (using const_cast).

Dimitri C.
A: 

You can use them together and you can do all sorts of things which ignore the const keyword, because that's all it is; a keyword. It tells the compiler that you won't be changing a variable which in turn allows the compiler to do some useful optomisations and stops you from changing things you didn't mean to.

Possibility.com has a decent article with some more background.

Jon Cage
+1  A: 

You can use them together. But you need to be consistent on your use of const because when C++ does name decoration, const is included in the type information that is used to decorate the symbol names. so extern const int i will refer to a different variable than extern int i

Unless you use extern "C" {}. C name decoration doesn't pay attention to const.

John Knoeller
+2  A: 
  • Yes, you can use them together.
  • And yes, it should exactly match the declaration in the translation unit it's actually declared in. Unless of course you are participating in the Underhanded C Programming Contest :-)

The usual pattern is:

  • file.h:
    extern const int a_global_var;
  • file.c:
    #include "file.h"
    const int a_global_var = /* some const expression */;

Edit: Incorporated legends2k's comment. Thanks.

edgar.holleis
Did you mean const `int a_global_var = <some_value_here>;`?
legends2k
I could not thing of the benefit of an extern const, and then it occurted to me that it will save bigtime on compile time when changing constants. Thanks
doron
Um, since `const` s are implicitly `static`, you need an `extern` even on the `a_global_var` definition (in *file.c*). Without this, anything that includes *file.h* will not link because it is looking for a `const int a_global_var` with external linkage.