How to understand const keyword in Cpp

From MetaSharp

Jump to: navigation, search

Article Author(s): Audric Thevenet
All Rights Reserved.


You can use multiple const keywords when declaring a variable. A nightmare to read when you don't know how. Here's the trick:

  • read declarations from the right to the left

example:

// ppi is a const pointer on a const pointer on a const integer
int const * const * const ppi;

What about this then?

// i is a const integer
const int i;

In fact the very first const can either be before or after the type name. Most of the time it'll be before.

// you'll never see this, because those 2 const keywords would apply to int type name
const int const i;

A last example:

// ppc is a const pointer on a variable pointer on a const char.
const char * * const ppc;
Personal tools