Type * var;
_ Type _ * _ var;
Any _ underscore can be replaced with const in above statement.
below are three valid statements.
const int *ptr; // ptr is a pointer to constant int int const *ptr; // ptr is a pointer to constant int (misleading but valid statement)
The Clockwise/Spiral Rule
Example #1: Simple declaration
+-----------+
| +-----+ |
| | +-+ | |
| | ^ | | |
int const *ptr; | |
^ ^ ^ | | |
| | +---+ | |
| +---------+ |
+----------------+
- Question we ask ourselves: What is ptr?
ptr is an…
- We move in a spiral clockwise direction starting with `ptr’ and we see the end of the line (the `;’), so keep going ptr is an …
- Continue in a spiral clockwise direction, and the next thing we encounter is the `*’ so, that means we have pointers, so… ptr is an pointer to…
- Continue in a spiral direction and we see the const so ptr is an pointer to constant …
- Continue in a spiral direction and we see the int
ptr is an pointer to constant int.
Example #2: Simple declaration
+--------------+
| +--------+ |
| | +-+ | |
| | ^ | | |
int * const ptr; | |
^ ^ ^ | | |
| | +------+ | |
| +------------+ |
+-------------------+
Question we ask ourselves: What is ptr? ptr is an...
- We move in a spiral clockwise direction starting with `ptr’ and we see the end of the line (the `;’), so keep going
ptr is an …
- Continue in a spiral clockwise direction, and the next thing we encounter is the const so, that means we have constant, so…
ptr is an constant …
- Continue in a spiral direction and we see the * so
ptr is an constant pointer to …
- Continue in a spiral direction and we see the int
ptr is an constant pointer to int
Example #3: Simple declaration
+-----------+ | +-----+ | | | +-+ | | | | ^ | | | const int *ptr; | | ^ ^ ^ | | | | | +---+ | | | +---------+ | +----------------+Question we ask ourselves: What is ptr?ptr is an…
- We move in a spiral clockwise direction starting with `ptr’ and we see the end of the line (the `;’), so keep going
ptr is an …
- Continue in a spiral clockwise direction, and the next thing we encounter is the `*’ so, that means we have pointers, so…
ptr is an pointer to…
- Continue in a spiral direction and we see the int so
ptr is an pointer to int …
- Continue in a spiral direction and we see the const
ptr is an pointer to int constant.So ptr is an pointer to constant int also means same thing in English as well as in c.Note: Spiral rule can be applied on any c declaration.