Stats

98 Contributors: 7 Tuesday, August 2, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

const keyword

Syntax

  • const Type myVariable = initial; // Declares a const variable; cannot be changed
  • const Type &myReference = myVariable; // Declares a reference to a const variable
  • const Type *myPointer = &myVariable; // Declares a pointer-to-const. The pointer can change, but the underlying data member cannot be changed through the pointer
  • Type * const myPointer = &myVariable; // Declares a const pointer. The pointer cannot be reassigned to point to something else, but the underlying data member can be changed
  • const Type * const myPointer = &myVariable; // Declares a const pointer-to-const.

Remarks

A variable marked as const cannot1 be changed. Attempting to call any non-const operations on it will result in a compiler error.

1: Well, it can be changed through const_cast, but you should almost never use that

Related Examples