读书笔记The Linux Kernel Primer: 2.5.4. const and volatile

These two keywords are the bane of many an emerging programmer. Theconst keyword must not be thought of as constant, but ratherread only. For example, const int *x is a pointer to a const integer. Thus, the pointer can be changed but the integer cannot. However,int const *x is a const pointer to an integer, and the integer can change but the pointer cannot. Here is an example ofconst:

-----------------------------------------------------------------------
include/asm-i386/processor.h
628  static inline void prefetch(const void *x)
629  {
630   __asm__ __volatile__ ("dcbt 0,%0" : : "r" (x));
631  }
-----------------------------------------------------------------------

The volatile keyword marks variables that could change without warning.volatile informs the compiler that it needs to reload the marked variable every time it encounters it rather than storing and accessing a copy. Some good examples of variables that should be marked as volatile are ones that deal with interrupts, hardware registers, or variables that are shared between concurrent processes. Here is an example of howvolatile is used:

-----------------------------------------------------------------------
include/linux/spinlock.h
51  typedef struct {
...
volatile unsigned int lock;
...
58  } spinlock_t;
-----------------------------------------------------------------------

Given that const should be interpreted as read only, we see that certain variables can be bothconst and volatile (for example, a variable holding the contents of a read-only hardware register that changes regularly).

This quick overview puts the prospective Linux kernel hacker on the right track for reading through the kernel sources.


const和 指针一起使用是C语言中一个很常见的困惑之处,在实际开发中,特别是在看别人代码的时候,常常会因为这样而不好判断作者的意图,下面讲一下我的判断原则:
const只修饰其后的变量,至于const放在类型前还是类型后并没有区别。如:const int a和int const a都是修饰a为const。*不是一种类型,如果*pType之前是某类型,那么pType是指向该类型的指针
const使用的基本形式: const type m;
一个简单的判断方法: 指针运算符*,是从右到左,那么如:char const * pContent,可以理解为char const (* pContent),即* pContent为const,而pContent则是可变的。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值