C++ const keyword

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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



Got any C++ Question?