IOS macro (define) and constant (const) understanding

Define and Const

Define and const are often used in iOS development. Let’s take a look at the difference between macro (define) and constant (const):

  • Define simply replaces text at compile time, and const is in the compile phase.
  • Define does not have any type checking, so there is no hint when type is wrong. Const has a type check and has an error prompt.
  • Define can define not only constants, but also methods. Constants (const) can only define constants and cannot define methods.
  • The const modifier has proximity, that is, the parameters after const are immutable. Const – modified parameters are read – only.
  • A lot of define will cause binary files to become larger. To compile time
    * compiler is usually not for ordinary const constant allocation of storage space, but they will be stored in the symbol table, which makes it become a constant during compilation, no storage and read operation of the memory, so that it is also very high efficiency
Note / const is a constant declaration, to ensure that it does not modify the. The difference that needs to be distinguished is that the const position is different: const, NSString, *text = @ ABCDE; //*text pointer cannot be modified, and text can be modified. NSString * const text = @ ABC '; //*text pointer can be modified, text cannot be modified.

Extern

  • Extern modifies a global variable that allows multiple files to be accessed
  • Variables modified with extern must be defined and can only be defined once. It is usually defined in the implementation file that is related to the header file that declares the constant. When you implement the file to generate the target file, the compiler allocates the storage space for strings in the data segment
.h extern NSString *const Test;.M NSString *const @ Test = "www.baidu.com"; / / this definition of constants is superior to the use of #define preprocessor directives, because the compiler will ensure a constant value unchanged. Once the.M file is defined, you can use it everywhere, and by using the preprocessing instructions, the definition constants may be inadvertently modified, resulting in different values used by each part of the application.