Lesson 111 +10 XP

Constants - const

const - Read-Only Data

const marks something as read-only; the compiler complains if you assign to it.

const int DAYS = 365;
DAYS = 400;   // error: assignment of read-only

const with pointers

const int *p;        // pointer to constant data
int *const p2;       // constant pointer
const int *const p3; // both

Why use const

  • States your intent clearly.
  • The compiler catches accidental writes.
  • Helps the optimizer generate better code.

TL;DR

  • Declare constants with const.
  • Const data cannot be reassigned.
  • Prefer const over magic literals.