Last active
July 7, 2019 18:35
-
-
Save matt-holden/9342289 to your computer and use it in GitHub Desktop.
[ int const * ] vs [ int * const ] vs [ int * const * ]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Most common & obvious usage | |
*/ | |
void constInt () { | |
int const x = 0; // the x variable can not be modified | |
const int y = 0; // this has the same meaning | |
} | |
/** | |
* A "constant pointer" to a changeable integer | |
*/ | |
void constPointerToInt () { | |
int a = 1; | |
int b = 2; | |
int * const c = &a; | |
// The value of the integer pointed to by 'z' is changeable, but 'z' | |
// cannot be reassigned. This is valid: | |
*c = 12345; | |
// But this is NOT valid. I can't re-assign the pointer to another address: | |
c = &b; // Error: read-only variable is not assignable | |
} | |
/* | |
* A changeable pointer to a 'constant integer' | |
*/ | |
void pointerToConstInt () { | |
// Given: | |
int a = 1; | |
int b = 2; | |
int const * c = &a; | |
// I can change WHERE c points to: | |
c = &b; | |
// But I cannot change the value at that address | |
*c = 123; // Error: Read-only variable is not assignable | |
} | |
/* | |
* A CONSTANT pointer to a CONSTANT integer | |
*/ | |
void constPointerToConstInt () { | |
// Given: | |
int a = 1; | |
int b = 2; | |
int const * const c = &a; // Notice the double-use of 'const' | |
// I cannot modify WHERE 'c' points | |
c = &b; // Error: Read-only variable is not assignable | |
// NOR can I modify the value it poitns to: | |
*c = 123; // Error: Read-only variable is not assignable | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment