I have this code line in my code.
what is void (*pfunc[3])()
?
uint32_t Var1 = 1, Var2 = 2, Var3 = 3;
void (*pfunc[3])();
pfunc[0] = Var1;
pfunc[1] = Var2;
pfunc[2] = Var3;
I have this code line in my code.
what is void (*pfunc[3])()
?
uint32_t Var1 = 1, Var2 = 2, Var3 = 3;
void (*pfunc[3])();
pfunc[0] = Var1;
pfunc[1] = Var2;
pfunc[2] = Var3;
The code snippet does not make sense.
This
void (*pfunc[3])();
is a declaration of an array of three elements of pointers to functions of the type void()
. Moreover there is nothing known about the function parameters.
On the other hand. this declaration
uint32_t Var1 = 1, Var2 = 2, Var3 = 3;
declares three objects of the type uint32_t
.
So the compiler should issue at least a warning that there is no implicit conversion from the type uint32_t
to the type void (* )()
for statements like this
pfunc[0] = Var1;
your example does not make too much sense bu
void foo()
{
printf("foo\n");
}
void bar()
{
printf("bar\n");
}
void goo()
{
printf("goo\n");
}
int main()
{
uint64_t Var1 = (uint64_t)foo, Var2 = (uint64_t)bar, Var3 = (uint64_t)goo;
void (*pfunc[3])();
pfunc[0] = (void (*)())Var1;
pfunc[1] = (void (*)())Var2;
pfunc[2] = (void (*)())Var3;
pfunc[0]();
pfunc[1]();
pfunc[2]();
}
Var1
, Var2
, Var3
keep addresses of the functions.
void (*pfunc[3])();
- declares an array of three function pointers
pfunc[2]();
- dereferences the functions pointer - ie calls the referenced function
PS uint64_t was used because integer has to have a size at least same as the size of the pointer. My system is 64 bits so the pointers are 64 bits.
Addendum to @VladfromMoscow's answer.
The syntax of the line you ask about can look a bit odd if you're not familiar with that sort of thing. If you re-state it as:
typedef void (*fn_ptr_t)();
// fn_ptr_t is a type of pointer, pointing to a function returning void and taking no arguments.
...
fn_ptr_t pfunc[3];
// an array of three fn_ptr_t's
then it might be a bit clearer. Specifically, your array declaration now looks like a 'normal' array (like int numbers[4]
for example).
You could argue that C's weird syntax has now pushed the confusion one step away into the typedef... Try this: Typedef function pointer?