本文介绍了“extern const” vs“extern”只要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了两种创建全局变量的方法,它们有什么区别,什么时候使用它们?

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

//.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 =\

总之,默认情况下使用const(前者)。编译器会让你知道你是否试图改变它 - 然后你可以决定是否代表你的错误,或者它指向的对象可能会改变。这是一个很好的保护措施,可以节省大量的错误/令人头疼的事情。

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

这篇关于“extern const” vs“extern”只要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:30