Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C function pointer syntax

Tags:

c

declare

My question is a very simple one.

Normally, when declaring some variable, you put its type before it, like:

int a; 

a function pointer may have type like: int(*)(int,int), in case we point to a function that takes two integers and returns an integer. But, when declaring such a pointer, its identifier is not after the type, like:

int(*)(int,int) mypointer; 

instead, you must write the identifier in the middle:

int(*mypointer)(int,int); 

why is this so? Sorry, I know it's an embarrassingly easy question...

Thanks to everybody for replying. A.S.

like image 541
user1941583 Avatar asked Jan 01 '13 22:01

user1941583


People also ask

What is the syntax of function pointer?

Function Pointer Syntaxvoid (*foo)( int ); In this example, foo is a pointer to a function taking one argument, an integer, and that returns void. It's as if you're declaring a function called "*foo", which takes an int and returns void; now, if *foo is a function, then foo must be a pointer to a function.

What is function pointer in C with example?

CServer Side ProgrammingProgramming. Function Pointers point to code like normal pointers. In Functions Pointers, function's name can be used to get function's address. A function can also be passed as an arguments and can be returned from a function.

Can we use pointer with function in C?

In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer.


1 Answers

I explain this in my answer to Why was the C syntax for arrays, pointers, and functions designed this way?, and it basically comes down to:

the language authors preferred to make the syntax variable-centric rather than type-centric. That is, they wanted a programmer to look at the declaration and think "if I write the expression *func(arg), that'll result in an int; if I write *arg[N] I'll have a float" rather than "func must be a pointer to a function taking this and returning that".

The C entry on Wikipedia claims that:

Ritchie's idea was to declare identifiers in contexts resembling their use: "declaration reflects use".

...citing p122 of K&R2.

like image 76
detly Avatar answered Oct 24 '22 02:10

detly