Pointer arthmatic 


A pointer can be implicitly converted into a bool. All non-null pointers are equivalent to true and the null one is false. The convention is that the null pointer correspond to a non-existing object.
Static pointers are not initialized to 0 when the program starts, so you have to be very careful when using this convention For example, if we want to write a function that count the number of characters into a character strings, and returns 0 if the parameter pointer is null :

#include <iostream>
int length(char *s) {
if(s) {
char *t = s;
while(*t != ’\0’) t++;
// The difference of two pointers is an integer
return t-s;

} else return 0; // the pointer was null
}
int main(int argc, char **argv) {
char *s = 0;
cout << length(s) << ’\n’;
s = "It’s not personal, it’s business";
cout << length(s) << ’\n’;
}

The delete and delete[] operators do not set the value of the deallo-
cated pointer to zero.
Designed By Blogger Templates | Templatelib & Distributed By Blogspot Templates