Explain the different positions of const with pointers.
0 upvotes
Practice with AISoon
The position of const relative to * determines what is read-only. Read declarations right-to-left:
c
const int *p; // pointer to const int — can't modify *p, can reassign pint * const p; // const pointer to int — can modify *p, can't reassign pconst int * const p;// const pointer to const int — can't modify either
In embedded systems, const int * is used for function parameters to promise the function won't modify the caller's data. int * const is used for memory-mapped register pointers that always point to the same address. const also helps the compiler place data in flash (.rodata) instead of RAM, saving precious RAM on small MCUs.
Source: C / C++ Concepts Q&A
