Pointer Type-Checking
C++ is stricter about pointer assignments than C is. You can't assign a pointer of one type or a numeric value to a pointer of a second type unless you use an explicit type cast.
int x; int * pi; short *ps; pi = &x; /* ok, both type int */ pi = 0xB8000; /* ok in C, invalid in C++ */ pi = (int *) 0xB8000; /* ok in C, C++ */ ps = pi; /* ok in C, invalid in C++ */ ps = (short *) pi; /* ok in C, C++ */
There are a couple of exceptions. In C++, as in C, you can assign a pointer of any type to a pointer-to-void, but, unlike C, you cannot assign a pointer-to-void to another type unless you use an explicit type cast.
int ar[5] = {4, 5, 6,7, 8}; int * pi; void * pv; pv = ar; /* ok in C, C++ */ pi = pv; /* ok in C, invalid in C++ ...
Get C Primer Plus®, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.