Skip to Content
C语言核心技术(原书第2版)
book

C语言核心技术(原书第2版)

by Peter Prinz, Tony Crawford
August 2017
Intermediate to advanced
798 pages
17h 44m
Chinese
China Machine Press
Content preview from C语言核心技术(原书第2版)
256
|
第
15
章
15.2 定义和使用宏
在
C
语言中,可以采用命令
#define
来定义宏。该命令允许把一个名称指定成任何所需的
文本,例如一个常量值或者一条语句。在定义了宏之后,无论宏名称出现在源代码的何
处,预处理器都会把它用定义时指定的文本替换掉。
关于宏的一个常见应用就是,用它定义数值常量的名称:
#define ARRAY_SIZE 100
double data[ARRAY_SIZE];
这两行代码为值
100
定义了一个宏名称
ARRAY_SIZE
,并且在数组
data
的定
义中使用了该
宏。惯例将宏名称每个字母采用大写,这有助于区分宏与一般的变量。上述简单的示例
也展示了宏是怎样让
C
程序更有弹性的。通常情况下,程序中往往多次用到数组(例如
上述
data
)的长度,例如,采用数组元素来控制
for
循环遍历次数。当每次用到数组长
度时,用宏名称而不要直接用数字,如果程序的维护者需要修改数组长度,只需要修改
宏的定义即可,即
#define
命令,而不需要修改程序中每次用到每个数组长度的地方。
在翻译的第三个步骤中,预处理器会分析源文件,把它们转换为预处理器记号和空白符
(请参见
1.7.1
节)。如果遇到的记号是宏名称,预处理器就会展开(
expand
)该宏;也
就是说,会用定义的文本来取代宏名称。出现在字符串字面量中的宏名称不会被展开,
因为整个字符串字面量算作一个预处理器记号。
无法通过宏展开的方式创建预处理器命令。即使宏的展开结果会生成形式上有效的命
令,但预处理器不会执行它。
在宏定义时,可以有参数,也可以没有参数。 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

数据库系统内幕

数据库系统内幕

Alex Petrov
精通機器學習

精通機器學習

Aurélien Géron
Go程序设计语言

Go程序设计语言

艾伦A. A.多诺万, 布莱恩W. 柯尼汉
算法精讲视频课程:24篇系列讲座

算法精讲视频课程:24篇系列讲座

罗伯特·塞奇威克, 凯文·韦恩(Kevin Wayne)

Publisher Resources

ISBN: 9787111562207