Bloomberg LP Interview Question
Software Engineer / DevelopersThe anonymous guy is not correct...
A const pointer is defined as "int * const ptr"..which means it can be made to point to an integer only once...and cannot be redirected to another...
Pointer to a const is declared as "int const * ptr"..which means it points to const integer and the pointer cannot be used to modify the value of integer it is pointing to
The anonymous guy is not correct...
A const pointer is defined as "int * const ptr"..which means it can be made to point to an integer only once...and cannot be redirected to another...
Pointer to a const is declared as "int const * ptr"..which means it points to const integer and the pointer cannot be used to modify the value of integer it is pointing to
Now consider the following three declarations assuming that char_A has been defined as a type char variable.:
const char * myPtr = &char_A;
char * const myPtr = &char_A;
const char * const myPtr = &char_A;
What is the difference between each of the valid ones? Do you know?
They are all three valid and correct declarations. Each assigns the addres of char_A to a character pointer. The difference is in what is constant.
The first declaration:
const char * myPtr
declares a pointer to a constant character. You cannot use this pointer to change the value being pointed to:
char char_A = 'A';
const char * myPtr = &char_A;
*myPtr = 'J'; // error - can't change value of *myPtr
The second declaration,
char * const myPtr
declares a constant pointer to a character. The location stored in the pointer cannot change. You cannot change where this pointer points:
char char_A = 'A';
char char_B = 'B';
char * const myPtr = &char_A;
myPtr = &char_B; // error - can't change address of myPtr
The third declares a pointer to a character where both the pointer value and the value being pointed at will not change.
const pointer:
- Anonymous November 04, 2008char const * p;
const char * p;
both are same. p can point anywhere u want, but, will not be allowed to modify any data using this pointer.
p[1] = 'a'; //error
pointer to const:
char a = 'a';
char * const p = &a;
p can't point anywhere else, but can modify a's data.
char b = 'b';
p = &b; //err
BONUS: const pointer to const data.
char const * const p = &a;
Effective C++ by Scott Meyers, Item 21: Use const whenever possible.