Link to home
Start Free TrialLog in
Avatar of CrypToniC
CrypToniCFlag for Sweden

asked on

Another casting question

Hi

One of my fellow co-workers said that double-casting
has no effect
such that code like
uint32 *value
value = (uint32*)((uint8 *)(some memory address));
is equivalent to
value = (uint32*)(some memory address);

is he correct ?

I would expect the result to be double casted

Consider memory looking like
01 02 03 04
I would then expect this
value = (uint32*)(some memory address);
to contain "04 03 02 01" (when printed)

and I would expect this
value = (uint32*)((uint8 *)(some memory address));
to contain "01 00 00 00" (when printed)

Comments ?

ASKER CERTIFIED SOLUTION
Avatar of Triskelion
Triskelion
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CrypToniC

ASKER

Don't you just hate when other people are right ?

:)

Thanks
/CrypToniC
Avatar of nebeker
nebeker

It depends on what you're casting.  In the example you've given, the cast really has no effect, because you're casting from one pointer type (uint8) to another pointer type (uint32).  All pointers are the same size, so there is really nothing to convert...

In your example, your casts are NOT dereferencing the memory address, so you aren't doing anything to change the value.

If you're casting between different types, then the double casting will most definitely have an effect.

If you wanted the above code to show the effects of the double cast, you would need to cast the _contents_ of the memory address, not the address itself, and to do that, you need to dereference the pointers...

For example:

uint32 *value;
uint32 x = 300;   /* for 'some memory address' */

If you do this:

value = (uint32*) (uint8 *) x;

then (*value) will be 300.

However, if you dereference the pointer, it will be converted to the type represented by that pointer.  For example:

value = (uint32*) * (uint8*) x;

then (*value) will be 44 (i.e. the lower 8 bits)...

Basically, if you have multiple casts, they will be evaluated one at a time, from right to left, causing a conversion each time.  So if you have the statement:

double x = (double)(float)(int)(short)(char) 0x1234567890;

the value "0x1234567890" will be truncated to the size of a char, then expanded to the size of a short, then an int, converted to a float, then to a double.