|
那本C语言陷阱与缺陷里面的
...
Armed with this knowledge, we are now prepared to tackle
(*(void(*)())0)(). We can analyze this statement in two parts.
First, suppose that we have a variable fp that contains a
function pointer and we want to call the function to which fp points. That is done this way:
(*fp)();
If fp is a pointer to a function, *fp is the function itself,
so (*fp)() is the way to invoke it. The parentheses
in (*fp) are essential because the expression would otherwise be interpreted as *(fp()).
We have now reduced the problem to that of finding
an appropriate expression to replace fp.
This problem is the second part of our analysis. If C could read our mind about types, we could write:
(*0)();
This doesn’t work because the * operator insists on having a pointer as its operand. Furthermore, the operand must be a pointer to a function so that the result of * can be called.
Thus, we need to cast 0 into a type loosely described as ‘‘pointer to function returning void.’’
If fp is a pointer to a function returning void,
then (*fp)() is a void value, and its declaration would look like this:
void (*fp)();
Thus, we could write:
void (*fp)();
(*fp)();
at the cost of declaring a dummy variable. But once we know how to declare the variable,
we know how to cast a constant to that type:
just drop the name from the variable declaration.
Thus, we cast 0 to a ‘‘pointer to function returning void’’
by saying:
(void(*)())0
and we can now replace fp by (void(*)())0:
(*(void(*)())0)();
The semicolon on the end turns the expression into a statement.
At the time we tackled this problem, there was no such thing as a typedef declaration. Using it,
we could have solved the problem more clearly:
typedef void (*funcptr)();
(* (funcptr) 0)();
...
看不大明白,高人指点一二,谢谢 |
|