GeeksforGeeks » C/C++ Programming Questions
several C++ interview questions
(4 posts)-
What's the output of the following C++ code, and how to analyze it?
int main (){
int ia[] = {1,2,3};
int *pia = ia;
const int *pci = pia;
int x = *pci;
*pci = 5;
int j = *(pci++);
}
-
The expression "const int* pci" declares a pointer pci to a constant location
Below line tries to modify value at a const location. So there is error in the code.
*pci = 5;
const int* ptr -----------> Pointer to a constant location, i.e, ptr can be changed but *ptr cannot be changed.
int* const ptr -----------> Constant Pointer to a location, i.e, *ptr can be changed but ptr cannot be changed. -
I think the mixing of const and * are not very intuitive to remember.
Anyone who can think of a better way to memorize that please write to magicgup@gmail.com to tell me, thanks in advance. -
const int* points to a read-only location. You may change the location, but then that new location becomes read-only.
int* const, on the other hand, fixes the memory location.
Reply
You must log in to post.