Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"extern const" vs "extern" only

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";
like image 314
Cananito Avatar asked Sep 03 '11 22:09

Cananito


People also ask

What does extern const mean?

In a const variable declaration, it specifies that the variable has external linkage. The extern must be applied to all declarations in all files. (Global const variables have internal linkage by default.) extern "C" specifies that the function is defined elsewhere and uses the C-language calling convention.

Can extern be const?

Yes, you can use them together.

How do I use extern in CPP?

Master C and Embedded C Programming- Learn as you goThe “extern” keyword is used to declare and define the external variables. The keyword [ extern “C” ] is used to declare functions in C++ which is implemented and compiled in C language. It uses C libraries in C++ language.

What does extern void mean?

extern void f(); declares that there is a function f taking no arguments and with no return value defined somewhere in the program; extern is redundant, but sometimes considered good style.


1 Answers

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
like image 130
justin Avatar answered Nov 03 '22 21:11

justin