#define, const, and typedef are often used when defining fields and types in iOS development, such as configuring parameters for production and testing different environments. So what’s the difference between them? Let’s take a look at them one by one.

_

1. Basic Concepts

1.1, # define

#define does not define global variables, but macro definitions. That is, it is not really used to define variables, but to do text substitution. When the program starts to run, the compiler replaces all the MAX in the code with 100 before compiling. As a result, #define does not occur during compilation, but during precompilation.

#define MAX 100 
Copy the code

Common uses of macros:

  • Common string macros: commonly defined colors, font sizes, etc

    #define kWaterAlpha 0.04F //

    #define kFlowRowSize 30 #define kFlowRowSize 30

    #define ROW_SIZE 20

  • Common code into macros: analogy singleton templates

    #define XRGB(r,g,b) [UIColor colorWithRed:(0x##r)/255.0 green:(0x##g)/255.0 blue:(0x##b)/255.0 alpha:1] #define kBgColor XRGB(f4, f4, f4) #define kBlackFontColor XRGB(33, 33, 33) #define kGrayFontColor XRGB(99, 99, 99) #define kBlueFontColor XRGB(3d,9a,e8)

    / / macro definition for current main interface rootViewController # define RootVC [UIApplication sharedApplication]. Delegate. Window. The rootViewController

    #define TopVC ([RootVC isKindOfClass:[UITabBarController class]]? [((UITabBarController *)RootVC).selectedViewController topViewController]:RootVC)

    #define DECLARE_DEFAULT +(instanceType)defaultInstance;

    #define IMPLEMENT_DEFAULT(C) +(instancetype)defaultInstance{

    static dispatch_once_t onceToken;

    static C *_gInstance;

    dispatch_once(&onceToken, ^{

    _gInstance = [C new];

    });

    return _gInstance;

    }

1.2, const

The const keyword is used to define constants. If a constant is decorated with const, its value cannot be changed. Compilers usually do not allocate storage for ordinary const constants. Instead, they are stored in a symbol table, making it a compile-time constant that does not store or read from memory, making it more efficient.

Common usage is as follows:

Const NSString *constString1 = @"I am a const NSString * string"; NSString const *constString2 = @"I am a NSString const * string"; NSString * const stringConst = @"I am a NSString * const string";Copy the code
  • ConstString1 is the same as constString2

  • The left-hand side represents the type information of the pointer itself, and const means that the address to which the pointer points is immutable

  • The right represents the variability of the pointer to the variable, that is, the variability of the variable stored in the memory cell to which the address of the pointer points ps; IOS development exchange technology group: welcome to join, no matter you are big or small white welcome to enter, share BAT, Ali interview questions, interview experience, discuss technology, we exchange learning and growth together

    1.3, typedef

    Typedefs are often used to alias a type (alias a known type). Often used to simplify complex types, variable types, and so on. A typedef is a type substitution, a type of statement that must end with a typedef; .

    // The iOS source code sets an alias for NSInteger, which stands for type long or int. #if __LP64__ || (TARGET_OS_EMBEDDED && ! TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64 typedef long NSInteger; typedef unsigned long NSUInteger; #else typedef int NSInteger; typedef unsigned int NSUInteger; #endifCopy the code

    Typedefs are probably the most commonly used in iOS development to define enumerations and blocks, as well as functions. The official API for typedef definition enumerations says so

    /* NS_ENUM supports the use of one or two arguments. The first argument is always the integer type used for the values of the enum. The second argument is an optional type name for the macro. When specifying a type name, you must precede the macro with 'typedef' like so: NS_ENUM supports one or two arguments. The first argument is usually an NSInteger type to specify the value type of the enumeration. The second argument is the alias of the optional enumeration type.  typedef NS_ENUM(NSInteger, NSComparisonResult) { ... }; If you do not specify a type name, do not use 'typedef'. For example: If you do not need a specific name, you do not need a typedef NS_ENUM(NSInteger) {... }; * /Copy the code

Typedefs are commonly used as follows:

typedef double NSTimeInterval; // Alias double NSTimeInterval typedef NSTimeInterval MyTime; // Call the NSTimeInterval alias MyTime typedef char * MyString; // Alias char * MyString //c format, alias Person structure MyPerson. Use :MyPerson p = {"jack"}; typedef struct Person { char *name }MyPerson; // In c format, alias Gender enumeration MyGender. Use :MyGender g = Man; typedef enum Gender { Man, Woman }MyGender; // In OC format, alias Gender enumeration MyGender. Use :MyGender g = Man; typedef NS_ENUM(NSInteger, Gender) { Man, Woman }; MyBlock typedef void(^MyBlock) (int a,int b); MyFunction typedef int(*MyFunction) (int a,int b);Copy the code

An example of a typedef defining a function:

int add (int a, int b){ return a + b; } typedef int(*MyMethod) (int a,int b); int main(){ MyMethod m = add; M (5, 6); // Call function return 0; }Copy the code

Second, the difference between

2.1 # define and const

  • Macros are processed at precompile time (macros are replaced before compilation begins); Const is processed at compile time

  • #define does not have a type, the macro does not do any type check, will not report a compilation error, just replace; Const constants, on the other hand, have a specific type and will be checked and will report a compilation error

  • Macros can define functions, methods; Const cannot

  • Using a large number of macros can easily lead to long compilation times and need to be replaced every time

  • Macros simply expand as many times as they are used, without allocating memory. (Macro definitions do not allocate memory; variable definitions do.) ; While const constants are allocated in memory (either in the heap or on the stack), const saves space and avoids unnecessary memory allocation

  • From an assembly point of view, const defines a constant as a memory address, rather than as an immediate number like #define. Therefore, a constant defined by const has only one copy during program execution. The constant defined by #define has several copies in memory.

  • Compilers usually do not allocate storage for ordinary const constants. Instead, they are stored in a symbol table. This makes them a compile-time constant and makes them efficient without storing and reading memory.

2.2 typedef and # define

  • defineIs a text replacement instruction that is part of a precompilation instruction and does not participate in compilation unless the text you want to replace has one;Otherwise, no need to add.typedefIt’s a type substitution, a type of statement, the endThere must be;
  • defineWhen written to a method/function, the scope is valid from where it was written until it is used#undef(If this instruction is not written, it will continue to be valid).typedefIf written in a method/function, the scope is valid only in that method/function.
  • If use theMyString s1,s2Is equivalent tochar *s1; char *s2;If you use #define MyString char *MyString s1,s2Is equivalent tochar *s1,s2namelychar *s1; char s2So againtypedefIs type substitution, directly involved in compilation, anddefineIt’s just simple text substitution.

typedef char * MyString;