"extern const" vs "extern" only

Cananito picture Cananito · Sep 4, 2011 · Viewed 11.6k times · Source

I've seen 2 ways of creating global variables, what's the difference, and when do you use each?

//.h
extern NSString * const MyConstant;

//.m
NSString * const MyConstant = @"MyConstant";

and

//.h
extern NSString *MyConstant;

//.m
NSString *MyConstant = @"MyConstant";

Answer

justin picture justin · Sep 4, 2011

the former is ideal for constants because the string it points to cannot be changed:

//.h
extern NSString * const MyConstant;

//.m
NSString * const MyConstant = @"MyConstant";
...
MyConstant = @"Bad Stuff"; // << YAY! compiler error

and

//.h
extern NSString *MyConstant;

//.m
NSString *MyConstant = @"MyConstant";
...
MyConstant = @"Bad Stuff"; // << NO compiler error =\

in short, use const (the former) by default. the compiler will let you know if you try to change it down the road - then you can decide if it was a mistake on your behalf, or if the object it points to may change. it's a nice safeguard which saves a lot of bugs/headscratching.

the other variation is for a value:

extern int MyInteger; // << value may be changed anytime
extern const int MyInteger; // << a proper constant