Programming in Objective-C 学习笔记06 —— Preprocessor

本文详细介绍了Objective-C预处理器的功能及使用方法,包括如何通过#define定义符号常量、宏及条件编译等内容,帮助读者更好地理解和掌握Objective-C编程的基础。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The Preprocessor

  • 从语言上定制Objective-C,使其适应自己的编程风格或特定的编程应用
  • 是编译过程的一部分,识别散布在程序中的特定语句
  • “#”开头

#define

  • 给符号名称指派程序常量(包括但不限于)
  • a defined name is not a variable; 字母全部大写
  • often placed toward the beginning of the program, after #import or #include, but not required; must be placed before it is referenced by the program.
  • more than a constant value: expression, “;”(所以不要用“;”结尾), 逻辑运算符, …
    • Careful:使用#define重新定义底层语言语法的行为不是好习惯(会让人费解)
  • 在#define语句中可以使用其他#define(不分前后)定义的符号名称
  • good use of #define often reduces the need for comments
  • macro 宏——常用带一个或多个参数的定义;
    • syntax——#define NAME(参数) (表达式(参数)); //参数和表达式都要用()括起来,确保完整替换
    • 简化表达式的编写
    • macro中也可以使用其他macro

#import

  • collect all your definitions into a separate file; import it and you can use
  • (in Xcode 5) “@import UIKit;” module (new feature)
  • 条件编译 Conditional Compilation
  • often used to create one program that can be compiled to run on different computer systems (for example, an iPhone versus an iPad)
  • switch on or off various statements in the program

条件控制语句

  • #ifdef,#endif,#else,#ifndef 语句
    • 检查某name是否已预编译(判断机型,系统,是否是debug状态……)
  • #ifndef 与#ifdef 功能相同,条件相反
  • if,#elif 语句——更加通用的条件编译控制
    • test whether a constant expression evaluates to nonzero.是就执行后面语句直到#else、#elif或#endif;否就直接跳过
    • #if defined (name) 与 #ifdef name 等价
    • 添加注释的新方法:“#if 0 …注释… #endif”
  • #undef 语句——remove the definition of a particular name :“#undef name”
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值