iOS基础-宏定义

宏定义

Macros

A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. There are two kinds of macros. They differ mostly in what they look like when they are used. Object-like macros resemble data objects when used, function-like macros resemble function calls.

You may define any valid identifier as a macro, even if it is a C keyword. The preprocessor does not know anything about keywords. This can be useful if you wish to hide a keyword such as const from an older compiler that does not understand it. However, the preprocessor operator defined (see Defined) can never be defined as a macro, and C++’s named operators (see C++ Named Operators) cannot be macros when you are compiling C++.

  • 宏是一个已被命名的代码片段。无论何时使用名称,它都被宏的内容所取代。
  • 有两种宏。它们的不同之处在于它们被使用时。
    • Object-like Macros :类对象的宏,封装使用的数据对象。
    • Function-like Macros :类函数的宏,封装函数的调用。
  • 任何有效的标识符都可以定义为宏。
    • 即使它是一个C关键字。预处理器对关键字一无所知。如果你想隐藏一个老编译器不识别的关键字如:const。
    • 定义的预处理器操作符(#if/#elif/...)不能定义为宏。如果定义的操作符是出现在宏扩展,那么C标准表示行为是未定义的。
    • c++的命名操作符(and/and_eq/or/or_eq/not/not_eq等11个)在编译c++时不能是宏。

Object-like Macros

  • 替换字符
  • 通常宏的名称都是用大写字母
#define BUFFER_SIZE 1024 
#define kTableViewCell @"TableViewCell" 
  • 在宏定义中,如果要换行,使用“"符号。然后经预处理后还是在同一行 ?
#define NUMBERS 1, \  
                2, \  
                3  
int x[] = { NUMBERS };  
     ==> int x[] = { 1, 2, 3 }; 
  • C预处理器是按顺序读取程序,因此宏定义生效在宏定义之后
foo = X;
#define X 4
bar = X;
// produces
foo = X;
bar = 4;
  • 宏调用时,预处理器在替换宏的内容时,会继续检测内容本身是否也是宏定义,如果是,会继续替换内容。
    • 注意,在定义 TABLESIZE 时没有定义 BUFSIZE。
      “#define” TABLESIZE 时使用了指定的宏定义 BUFSIZE,这时不检查 BUFSIZE 是否也包含宏定义。只有当你使用 TABLESIZE 时,它的扩展才会扫描更多的宏定义。
#define TABLESIZE BUFSIZE
#define BUFSIZE 1024
TABLESIZE
     → BUFSIZE
     → 1024
  • 宏定义以最后生效的定义为准
#define BUFSIZE 1020
#define TABLESIZE BUFSIZE
#undef BUFSIZE
#define BUFSIZE 37
        → 37

Function-like Macros

未完待续

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容