int * const x; (const pointer vs. const data)

The example within the title shows a typical pointer declaration containing the const keyword: “int * const x;”. If you write or read such a declaration you may be confused and ask yourself whether the pointer or the data is constant.

There is a simple principle which helps to read such declarations: Read it backwards. In the example, you therefore read: x is a constant pointer to an int.

The following examples show some declarations with constant pointers and/or constant data. By using the “read it backwards” principle, these declarations are easy to understand.

int* x;   // pointer to int
  
const int* x;   // pointer to constant int
int const* x;   // pointer to constant int

int* const x;   // constant pointer to int
  
int const * const x;   // constant pointer to constant int
const int * const x;   // constant pointer to constant int
  
int** x;    // pointer to pointer to int

const int** x;   // pointer to pointer to constant int
int const** x;   // pointer to pointer to constant int

int* * const x;   // constant pointer to pointer to int

int* const * const x;   // constant pointer to constant pointer to int
Werbung
Dieser Beitrag wurde unter C++ veröffentlicht. Setze ein Lesezeichen auf den Permalink.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden /  Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s