LearnFrenzy
Sign in Take a free test

C Programming · Topic 11 of 23

C Const

  • 4 exercises
  • 40 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

C Const · Study material

The const keyword in C marks an object as read-only: once initialised, the program may not change it through that name. const documents intent, lets the compiler catch accidental writes, and lets it place data in read-only memory. But C's const is subtler than it looks: a const variable is not a compile-time constant in C, const int *p and int *const p mean different things, and casting const away can crash a program. This page explains all of it, compares const with #define, enum and C23's constexpr, and gives you 40 practice questions checked on a real compiler.

On this page

  • const variables, and four ways to name a constant
  • const with pointers: pointer to const, const pointer, both
  • const-correct functions, structures and lookup tables
  • What C23 constexpr adds, and why casting away const is dangerous

Four ways to name a constant

FormHas a type?Constant expression?Scope
#define MAX 100No (text replacement)Yesnone – from the #define to the end of the file
enum { MAX = 100 };intYesnormal C scope
const int max = 100;YesNo (in C; it is in C++)normal C scope
constexpr int max = 100; (C23)YesYesnormal C scope

"Constant expression" matters for global and static array sizes, case labels, bit-field widths and static initialisers. Before C23, typed constants for those uses had to be enums or macros.

#include <stdio.h>

#define MAX_USERS 100              /* text replacement: no type, no scope */
enum { MAX_RETRIES = 3 };          /* an int constant expression */
static const double TAX = 0.18;    /* a typed, read-only variable */

int main(void) {
    int slots[MAX_RETRIES];        /* enum constants can size arrays */
    slots[0] = MAX_USERS;
    printf("%d %d %.2f %zu\n", slots[0], MAX_RETRIES, TAX, sizeof slots / sizeof slots[0]);
    return 0;
}

Output

100 3 0.18 3

const with pointers

Read a declaration from right to left. The const applies to what is on its left, or to the right if nothing is on its left.

DeclarationRead it asChange *p?Change p?
const int *p = int const *pp is a pointer to a const intNoYes
int *const pp is a const pointer to an intYesNo
const int *const pp is a const pointer to a const intNoNo
#include <stdio.h>

int main(void) {
    int a = 1, b = 2;
    const int *p = &a;       /* pointer to const int: *p cannot be changed through p */
    int *const q = &a;       /* const pointer: q cannot point anywhere else */

    p = &b;                  /* allowed: p itself is not const */
    *q = 10;                 /* allowed: the int q points to is not const */
    printf("%d %d %d\n", *p, a, *q);
    return 0;
}

Output

2 10 10

"Pointer to const" means "read-only through this pointer". The object itself may still change through another name.

const-correct functions

Mark pointer parameters const when the function only reads through them. Callers can then pass both modifiable and read-only data (a char * converts to const char * automatically, but not the other way round), and the compiler stops the function from writing by accident.

#include <ctype.h>
#include <stdio.h>

size_t count_upper(const char *s) {          /* a promise: s is only read */
    size_t n = 0;
    for (; *s; s++)                          /* moving s is fine: the characters stay untouched */
        if (isupper((unsigned char) *s))
            n++;
    return n;
}

int main(void) {
    char name[] = "LearnFrenzy C23";
    printf("%zu %zu\n", count_upper(name), count_upper("Hello"));   /* char * converts to const char * */
    return 0;
}

Output

3 1

const structures and tables

static const data – lookup tables, default settings, message strings – is placed in read-only memory and cannot be corrupted. Copy it into a normal variable when you need a changeable version.

#include <stdio.h>

struct config {
    const char *name;
    int port;
};

static const struct config defaults = {"server", 8080};    /* read-only defaults */

int main(void) {
    struct config c = defaults;      /* copy the defaults ... */
    c.port = 9090;                   /* ... and change only the copy */
    printf("%s %d %d\n", c.name, c.port, defaults.port);
    return 0;
}

Output

server 9090 8080

C23: constexpr

C23 adds constexpr for objects: a typed constant that is a true compile-time constant, so it can size static arrays and appear in case labels – the job enums and macros used to do. Its initializer must itself be a constant expression.

#include <stdio.h>

int main(void) {
    constexpr int SIZE = 4;              /* C23: a true compile-time constant */
    static int table[SIZE];              /* a static array needs a constant size */
    constexpr double RATE = 0.5;
    switch (2) {
    case SIZE / 2:                       /* usable in case labels, too */
        puts("case uses constexpr");
        break;
    }
    printf("%zu %.1f\n", sizeof table / sizeof table[0], RATE);
    return 0;
}

Output

case uses constexpr
4 0.5

Casting away const

A cast such as (int *) &limit silences the compiler, but writing to an object that was defined const is undefined behaviour: the data may live in read-only memory, and the program crashes. Casting away const is only safe when the object itself was not defined const. volatile const describes the remaining case – data the program must not write but that can change on its own, such as a hardware status register.

Key points to remember

  • A const object must be initialised and cannot be assigned afterwards.
  • In C, a const variable is not a constant expression – use enum, #define or C23 constexpr for array sizes and case labels.
  • const int *p: read-only data. int *const p: fixed pointer.
  • Make read-only pointer parameters const.
  • Never write through a pointer obtained by casting away const from a const object.

Frequently asked questions

What is the difference between const and #define?

#define is a preprocessor text substitution with no type and no scope; const creates a typed object that obeys scope and can be inspected in a debugger. In C, only the macro is a constant expression (until C23 constexpr).

Can a const variable be changed?

Not through its own name, and writing to a const-defined object by any means is undefined behaviour. Data behind a "pointer to const" can still change through other, non-const names.

Why does const int N = 10; int a[N]; work inside a function but not at file scope?

Inside a function, a becomes a variable length array. At file scope VLAs are not allowed, and N is not a constant expression in C.

Where can I learn more?

Read Constants in C and Pointers in C Explained, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C Programming

C programming is the language most computer science courses start with and the foundation of operating systems, embedded devices and compilers. This section helps you learn C properly – data types, operators, control statements, functions, arrays, strings, pointers, structures, memory allocation and files – and then prove it with hundreds of practice questions explained line by line.

Why it matters

  • C teaches how a computer really works: memory, addresses and how data is stored
  • Pointers and memory questions are a favourite in written tests and technical interviews
  • Once you know C, learning C++, Java and Python becomes much easier
  • Embedded systems, operating systems and many companies' coding rounds still use C

Who it is for

  • School students (Class 11–12 computer science) building a strong programming base
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, aptitude-cum-coding tests and technical interviews
  • Anyone preparing for GATE CS or government IT exams

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro tests
  • Technical interviews
  • GATE CS
  • University exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links