Why cant this happen?

Why cant a pointer of type long point to variable of type int?

Essentially all pointers do is hold addresses so why cant this happen?
closed account (zb0S216C)
It's how the compiler interprets the data pointed-to by a pointer and C++'s type-system. Firstly, pointers must point to the storage they were intended to point to, except when inheritance is concerned.

Secondly, there's no guarantee that the size of "long" will be equal to that of "int". Casting from one integral type to another isn't safe in some cases because of the possibility of truncation. For instance, casting from an "int *" to an "long *" is safe because the standard guarantees that "sizeof( long )" must match or exceed the numercial range of "sizeof( int )", like so:

1
2
3
4
int *Pointer_A_( ... );
long *Pointer_B_( static_cast< long * >( Pointer_A_ ) );

*Pointer_B_ = ...; // Safe 

Here, the size of storage pointed-to by "Pointer_B_" is guaranteed to hold the value pointed-to by "Pointer_A_". However, when casting from "long *" to "int *", there's a possibility of truncation, because "long" may hold a larger numerical range than "int"; therefore, the following will cause a truncation if "sizeof( long )" is greater than "sizeof( int )":

1
2
3
4
5
6
7
8
// Assumed sizes:
// long: 8-bytes
// int: 4-bytes

long Value_( unsigned int( -1 ) + 100 );
long *Pointer_A_( &Value_ );

unsigned int *Pointer_B_( static_cast< unsigned int * >( Pointer_A_ ) );

Here, "Pointer_A_" is pointing to an 8-byte block of storage which contains a value that a 4-byte block of storage cannot handle. When the address of "Value_" is read as an "unsigned int", the value of "Value_" is truncated so that the value fits within 4-bytes.

[Note: The above casts may not be taken too kindly by your compiler -- your mileage may vary. --end note]

Wazzak
@ Anmol444: maybe you could try the void pointer void* if you want a "universal" pointer type.

Of course, you will have to cast it whenever you dereference it.
Topic archived. No new replies allowed.