This question already has an answer here:
Here is a code that purpose is to set the program counter to jump to address 0x1000
. I know what it does but I don't understand how. It is related to my lack of C language knowledge. May be you can enlighten me. Here is the statement/function (I even don't know what it is :))
((void (*)())0x1000)();
I thing it is pointer to a functions that returns void
and accepts no argument. Please correct me if I am wrong.
A constant
gets cast to a type:
The type is
void (*)()
— a pointer (asterisk) to a function which takes no parameters (empty parentheses on the right) (oops, see the comment by pmg) and returns no value (void
on the left). Additional parens on the asterisk prevent associating it tovoid
, which would incorrectly create avoid *
type here.So after the cast you have a pointer to a parameter-less void function at the addres 0x1000:
And that function...
gets called by adding an empty parameters list:
(void (*)())
is a pointer to a function returningvoid
and taking an unspecified, but fixed, number of arguments.(void (*)())0x1000
is casting the literal0x1000
to the above type.Finally, the suffixed
()
calls that function. The expression preceding that needs to be in brackets otherwise the suffixed()
will bind to the0x1000
which is not syntactically valid.It's down to you to check if the casting is actually valid. If not then the behaviour of your program is undefined.
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:
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.
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 ofp
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:
The person who wrote that code should have rewritten it in a readable manner as:
What the code does is now pretty much self-documented.