Skip to study material
← Question index

QUESTION 30 · Qualifiers and Preprocessor

Explain const, volatile and restrict type qualifiers.

5 marks

Answer in brief

Type qualifiers add properties to a type. The main introductory qualifiers are const, volatile and restrict; C11 also includes _Atomic with separate atomic-operation rules.

Const

const int limit = 10; declares an object that cannot be assigned a new value through limit. A pointer to const can be used to allow reading without allowing modification through that pointer. const does not automatically make a C object an integer constant expression. Casting away const does not make an originally const-defined object safely writable.

Volatile

volatile tells the implementation that accesses to an object have significance beyond ordinary calculations. It is used in implementation-specific hardware interfaces and suitable signal-handling situations. It does not guarantee atomic updates, mutual exclusion or thread synchronisation. A variable changing between threads needs the appropriate atomic or locking rules.

Restrict

restrict is mainly used with pointer types. It expresses an access promise about the objects reached through pointers during the relevant execution. This can help optimisation when the promise is valid. It does not check the promise at runtime; violating the required access rules can cause undefined behaviour. Full pointer examples are deferred to Unit V.

Simple example

The program declares a const rate and uses it to compute an amount. The rate can be read, but an assignment such as rate = 0.10 is not allowed through that name. The program does not contain that invalid assignment.

Important distinction

Qualifiers are not storage classes. A const object can still be an automatic local or have static storage duration, depending on its declaration. Qualifying a type does not by itself select a hardware memory location.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
    const double rate = 0.05;
    double amount = 200.0 * rate;
    printf("Amount = %.2f\n", amount);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Amount = 10.00