Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

const — type qualifier

const prevents modification through a qualified expression; with pointers, it can qualify the pointed-to object or the pointer itself.

Version: C23; repository compiler flag, production runtime not attested

Syntax

const T object = value;
const T *pointer;
T mutable_object = value;
T * const fixed = &mutable_object;
const T * const fixed_view = &object;

const is a type qualifier. const int limit = 10; defines a nonmodifiable object; int const denotes the same type. const alone does not make the name an integer constant expression.

const int *p prevents writing through *p, but permits changing p. int * const p = &value fixes the pointer, not the value. const int * const p = &value imposes both restrictions.

A const view does not freeze an originally modifiable object: another pointer can change it. However, modifying an object defined as const, even after casting away the qualifier, causes undefined behavior.

In the example, fixed changes value; view reads the updated value.

Examples

#include <stdio.h>

int main(void)
{
    int value = 4;
    const int limit = 10;
    const int *view = &value;
    int * const fixed = &value;

    *fixed = 7;
    printf("%d %d\n", *view, limit);
    return 0;
}

Result

7 10

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources