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使用的基本形式: const type m;