Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

c - What does `((void (*)())0x1000)();` mean?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

C declarations are decoded from inside out using a simple rule: start from the identifier and check on the right side for [] (array) or () (function) then check on the left side for the type of the values (stored in the array or returned by the function), without crossing the parentheses; escape from the parentheses and repeat.

For example:

void (*p)()

p is (nothing on the right) a pointer (on the left, don't cross the parentheses) to (escape the parentheses, read the next level) a function (right) that returns nothing (left).

When the identifier (p in this case) is missing, all that remains is a type declaration.

A type enclosed in parentheses, put in front of a value is a type cast.

(void (*)())0x1000

converts the number 0x1000 to a pointer to a function that doesn't return anything (see what's outside the parentheses in the paragraph about the declaration of p above).

On the next level, the expression above (a pointer to a function can be used in the same way as a function name) is used to execute the code pointed at.

See below the entire expression de-composed:

(
  (
    void (*)()   /* type: pointer to function that doesn't return anything     */
  )0x1000        /* value 0x1000 treated as a value of the type declared above */
)                /* enclose in parentheses to specify the order of evaluation  */ 
();              /* the pointer above used as a function name to run the code  */

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...