搬运工--C关键字union/const/define/typedef/extern/volatile

本文总结了C语言中的几个重要关键字:Union用于节省存储空间,Const表示不可变的值,Define常用于宏定义,Typedef用于创建新的类型别名,Extern声明外部变量,Volatile则用于指示变量可能被隐含改变。文中对每个关键字的用途、应用场景和潜在风险进行了详细阐述,并提供了相关实例。

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

C语言中有32个保留关键字,C99和C11又分别增加了一些关键字,我挑出了几个总结一下,由于内容较多,这里只是提供一个总览,细节问题请自行查看链接。

Union

1.Union Type--Wiki
union本身不难理解:
The primary usefulness of a union is to conserve space, since it provides a way of letting many different types be stored in the same space.
Structure and union specifiers have the same form. [ . . . ] The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit-field, then to the unit in which it resides), and vice versa.
—ANSI/ISO 9899:1990 (the ANSI C standard) Section 6.5.2.1
Unions can also be anonymous; that is, they do not have a name. Their data members are accessed directly.

2.对Union的进一步认识与一些深层应用
写了一些union的具体例子,比如在socket编程中的应用

3.Union用法举例
举了一些例子,比如在判断大尾/小尾系统时的应用

Const

1.Constant--Wiki
Const means that its value will be set at compile time and should not be changeable at runtime.
"Dynamically-valued constants"这一部分看得比较晕,不知道究竟什么意思

2.指针与const限定符
指针+const的用法,写的很清晰

3.1const与函数
3.2c++ 函数后面 const 作用
这两个个比较偏向C++

Define

1.define总结
define的内容不是很多,这一篇介绍的比较全面了

2.#define、const、typedef的差别
这个是老生长谈了

Typedef

1.揭秘 typedef四用途与两陷阱
写的很好,解答了指向函数的指针的问题,比如:typedef void(*PTR) (int)

2.Linux kernel coding style
"Linux kernel coding style Chapter 5: Typedefs"提到关于typedef的建议,强烈建议大家看看,
特别是typedef不要大量的声明结构体

Extern

1.External variable
Extern的解释

2.用extern声明的变量和函数在编译阶段不会进行类型检查,因此编译速度比较快,但有潜在的危险,如果变量或者函数声明与定义不一致,编译可能可以通过,但运行时可能会出错。用extern声明的函数可以用包含函数对应的头文件的方法来代替。

Volatile

1.Volatile变量--Wiki
通常,volatile关键字用来阻止(伪)编译器对那些它认为变量的值不能“被代码本身”改变的代码上执行任何优化。

2.Why the "Volatile" type class should not be used? -- Kernel Document
The key point to understand with regard to volatile is that its purpose is to suppress optimization, which is almost never what one really wants to do. In the kernel, one must protect shared data structures against unwanted concurrent access, which is very much a different task. The process of protecting against unwanted concurrency will also avoid almost all optimization-related problems in a more efficient way.

3.正确使用Volatile变量--IBM developerWorks
Java中,Volatile不具备原子操作,线程能够自动发现Volatile变量的最新值.
(自己理解为线程维护了Volatile变量的一份拷贝,但在每次用到这个变量时重新读取.)

4.C语言中Volatile关键字的作用
解释了const / volatile / 指针的相关内容

Restrict/Inline是C99新增的关键字,没有用过,就先不写了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值