What does this c code do?
{
int (*func)();
func = (int (*)()) code;
(int)(*func)();
}
Especially I confused about subj.
What does this c code do?
{
int (*func)();
func = (int (*)()) code;
(int)(*func)();
}
Especially I confused about subj.
It's a cast to a function pointer.
The sequence int (*)()
is for a function pointer that takes an indeterminate number of arguments, and returns an int
. Wrapping it in parentheses like (int (*)())
, when combined with an expression, is casting the result of the expression.
The code you present, with comments:
// Declare a variable `func` which is a pointer to a function
int (*func)();
// Cast the result of the expression `code` and assign it to the variable `func`
func = (int (*)()) code;
// Use the variable `func` to call the code, cast the result to `int` (redundant)
// The returned value is also discarded
(int)(*func)();
Remember to do a typecast, we use the following:
(type_to_cast) value;
when you want to cast some value
to a certain type
.
Also remember you define a function pointer as
return_type (*pointer_name) (data_types_of_parameters);
And the type of a function pointer is
return_type (*) (data_types_of_parameters)
Finally, you can call a function with its pointer as
(*func_pointer)(arguments);
So, with those 4 points in mind, you see that your C code:
First defines a funciton pointer func
.
Second, casts code
as a function pointer and assign its value to func
Third, calls the function pointed by func
, and casts the value reutrned to int
.
int (*func)();
declares func
as a pointer to a function that takes any number of parameters and and return int
.
In statement func = (int (*)()) code;
, a cast is applied to code
and then assign it to the function pointer func
.
(int)(*func)();
doesn't make much sense. Cast is not needed and it discards the return value. The call should be simply like
int var = func();
or
int var = (*func)();