“extern const” vs “extern” only

2019-03-11 02:21发布

问题:

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";

回答1:

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