user3079266
user3079266

Reputation:

C - function pointer types with named parameters

On MSVC and gcc (GCC) 4.8.3 20140911 the following compiles and runs just fine:

#include <stdio.h>

int func(int a, int b){
    return 0;
}

int main(void){
    int (*funcPointer)(int a, int b);

    funcPointer = func;

    printf("funcPointer = %p\n", funcPointer);

    return 0;
}

Is such behaviour well-defined, or is it non-standard and it's actually illegal for function pointer types to have named parameters (i.e. names as well as types in their parameter list)?

Upvotes: 3

Views: 676

Answers (3)

Gopi
Gopi

Reputation: 19864

You can have a parameter in your function pointer. It is totally valid. The parameter list matches that of the function being called and the names is just optional.

It can also be written as

int (*funcPointer)(int,int);

I mean

int (*funcPointer)(int a, int b);

This is valid and you can verify the same by calling

int res = funcPointer(3,4);

and returning

int func(int a, int b){
    return a+b;
}

Upvotes: 5

Serve Laurijssen
Serve Laurijssen

Reputation: 9733

A question in the answer:

Why does this compile and what does it mean?

int func(int a) { return a; }

int main(int argc, char **argv)
{
    int(*a)(int x(float)) = func;

    printf("%d\n", a(1));

    return 0;
}

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249153

It's perfectly legal. The names a and b in funcPointer are not used for anything, but they are permitted. You could use any (legal) names you want, they don't matter at all.

Upvotes: 1

Related Questions