Friday, July 29, 2016

C Basics – Const and Volatile - Type Qualifiers in C

In C, a type qualifier is a keyword that is applied to a type, resulting in a qualified type. For example, const int is a qualified type representing a constant integer, while int is the corresponding unqualified type, simply an integer.

Type qualifiers are a way of expressing additional information about a value through the type system, and ensuring correctness in the use of the data.

Const:
The const type qualifier declares an object to be nonmodifiable.

In C, a type is given in a function declaration or variable declaration by giving one or more type specifiers, and optionally type qualifiers. For example, an integer variable can be declared as:
int x;
where int is the type specifier.

An unsigned integer variable can be declared as:
unsigned int x;
where both unsigned and int are type specifiers.

A constant unsigned integer variable can be declared as:
const unsigned int x;
where const is a type qualifier, which the qualified type of x is const unsigned int and the unqualified type is unsigned int.

A const variable can be initialized or can be placed in a read-only region of storage. The const keyword is useful for declaring pointers to const since this requires the function not to change the pointer in any way.

Volatile:
The other qualifier in C, volatile, indicates that an object may be changed by something external to the program at any time and so must be re-read from memory every time it is accessed.

The volatile type qualifier declares an item whose value can legitimately be changed by something beyond the control of the program in which it appears, such as a concurrently executing thread.

The qualifier is most often found in code that manipulates hardware directly and in multithreaded applications. It can be used in exactly the same manner as const in declarations of variables, pointers, references, and member functions. It can be combined with the const qualifier as in this sample:

const volatile int cvint; /* Constant Volatile integer */

Use volatile with data objects that may be accessed or altered by signal handlers, by concurrently executing programs, or by special hardware such as memory-mapped I/O control registers.



Related topics:
Data Types - Type Specifiers in C   |   Variables in C   |   Local and Global Variables in C   |   Constants in C   |   Initialization in C

List of topics: C Programming

No comments:

Post a Comment