Pointer Type-Checking

I l @ ve RuBoard

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++ */ pi = (int * ) pv;  /* ok in C, C++            */ 

The other exception in C++ is that you can assign the address of a derived-class object to a base-class pointer, but that relates to features that don't even exist in C.

I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net