Static, const, and macro views

Many friends are confused about static, const and macro. The following are personal opinions! Thank you. It’s a bad place. Welcome!

1: the advantages and disadvantages of macro and const:

The thing that 1.static and const have in common is that they can only allocate one memory;

2. macro, then every place to use to allocate memory

3. compile time: macro is pre compiled (compiled prior to processing), const is the compile phase.

4., compile check: macro do not check, will not report compilation errors, just replace, const will compile the check, will report a compilation error.

5. macro benefits: macros can define some functions, methods. Const can not.

6. macro disadvantages: the use of a large number of macros, easy to compile a long time, each time you need to replace.

The following are their usage and function:

Two: use the const to modify the constant

Example: const, NSString, *name = @ jack”;

Const modifies global constants, which can be accessed in any file! In other files, extern, NSString, *name; ways to access, you can change the value of other documents, a change, and other places will change

If you feel extern NSString *name; this is too much trouble, can provide in the definition of global.H file under constant external access: UIKIT_EXTERN const NSString *name constant; then use this variable in other places, where the constant import header file. It can be accessed directly with the constant name. It can also be modified, and it will be changed elsewhere!

If we want to write a global constant, but do not want to be modified, you can write NSString * const name = @ jack; if you want to modify it outside, you will be wrong! The following two forms of writing can be modified in the outside;

Const NSString *name = @ jack”;

NSString const *name = @ jack”;

Three: use static to modify variables, static is static local variable

Example: static, NSString, *name = @ jack”;

You can only use this constant in this file, you can’t be modified, the change will be wrong, and the static keyword will be added before the return type of the function. The function is defined as a static function. A static function is different from an ordinary function. It can only be visible in the file that declares it, and cannot be used by other files. The benefits of defining static functions:

Static functions cannot be used by other files;

Functions in other documents that define the same name do not conflict;

Three: static, const, joint modification constants

Static, const, NSString, *name = @ jack”;

This constant can only be used in this document, which can be modified, changed, and changed elsewhere