Parse this Expression !
Can anyone parse this following expression f开发者_StackOverflow中文版or me
#define Mask(x) (*((int *)&(x)))
I applied the popular right-left rule to solve but cant.. :(
Thanks a bunch ahead :)
This just reads out the first sizeof (int)
bytes at the address of the argument, and returns them as an integer.
This defines a macro Mask that interprets its argument as an int.
&(x)
- address of x...
(int *)&(x)
- ...interpreted as a pointer to int
*((int *)&(x))
- the value at that pointer
You need to think inside out:
- Find the address of x.
- cast this to an integer pointer
- dereference this pointer to return the value.
As such, int y = Mask(something);
returns an integer interpretation of something
.
To keep it simple:
#define Mask(x) reinterpret_cast<int&>(x)
I am assuming that there is no const_cast
, that is, that the argument x
is of non-const type, else there would be an extra const_cast
in there.
This kind of macro can cast a float
value to a DWORD
in it's binary form and vice versa. This can be used with libraries that have functions using DWORD
as generic input types.
An example would be SetRenderState()
in DirectX :
HRESULT SetRenderState(
D3DRENDERSTATETYPE state,
DWORD value
);
In this particular case, some state
require you to give a float
value. Now, trying to pass 6.78f
directly to that function would truncate 6.78f
to an integer which would be 6
. What we want is the binary form 0x40D8F5C3
so that the library will be able to cast it back to 6.78f
.
That's what we call a reinterpret cast. It's platform dependent and potentialy dangerous unless you know what you are doing.
精彩评论