`const` — C Keyword

`const` — C Keyword

The const keyword in C: marks an object as non-modifiable.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

const (C)

Marks an object as non-modifiable after initialization. Attempting to write to a const-qualified object is undefined behavior.

Syntax

const Type name = value;
const Type* ptr;        /* pointer to const (read-only target) */
Type* const ptr;        /* const pointer (fixed address) */
const Type* const ptr;  /* both const */

Example

#include <stdio.h>
#include <math.h>

const double PI = 3.14159265358979;

double circle_area(double r) {
    return PI * r * r;
}

/* const pointer-to-char: string contents are read-only */
int str_len(const char* s) {
    int len = 0;
    while (*s++) ++len;
    return len;
}

int main(void) {
    /* PI = 3.0;   -- error: assignment of read-only variable */
    printf("%.4f\n", circle_area(5.0));
    printf("%d\n", str_len("hello"));   /* 5 */
    return 0;
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}