开发者

"extern const" vs "extern" only

开发者 https://www.devze.com 2023-04-02 10:54 出处:网络
I\'ve seen 2 ways of creating global variables, what\'s the difference, and when do you use each? //.h

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";
开发者_StackOverflow社区

and

//.h
extern NSString *MyConstant;

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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消