c - What's the difference between these 2 declarations? -


here's simple , delicate question. explain difference between , b?

void (*a)(int x, int y) void (*b(int x, int y))(int) 

this question arise following linux function declaration:

void (*signal(int sig, void (*func)(int)))(int); 

solution

the following program makes demo.

#include <signal.h> #include <stdio.h> #include <unistd.h>  void ouch(int sig) {    printf("ouch! - got signal %d\n", sig);    signal(sigint, sig_dfl); }   void (*g())(int) // b {    return ouch; }  int main() {     void (*f)(int); //    f=g();    signal(sigint, f);     while(1)    {       printf("hello, world!\n");       sleep(1);    } } 

the designers of c chose name types in way use case of type matches, closely possible, way in use type value. so, example, when have declaration like

int a; 

you can a int. if have type like

int *a; 

then have dereference a writing *a int.

you can use similar, albeit more complex, logic decode types posted. let's start with

void (*a)(int x, int y) 

this says if dereference a (by writing *a), you're left looks like

void (int x, int y) 

which function taking in 2 ints , returns void. in other words, can think of a pointer function; once dereferenced, function.

now beast:

void (*b(int x, int y))(int) 

this one's trickier. idea follows. if take b , pass in 2 arguments it, looks this:

void (*)(int) 

which pointer function taking in int , returning void. in other words, b function takes 2 arguments, returns function pointer takes 1 argument , returns void.

it's tricky decode these types, don't seem them written way , instead use typedef simplify things. example, typedef:

typedef void (*functiontakingtwoints)(int, int); 

says can use functiontakingtwoints define function pointer points @ function takes in 2 ints , returns void. here, declaration of a simplifies down to

functiontakingtwoints a; 

similarly, in case of b, let's define type

typedef void (*functiontakingoneint)(int); 

now, can rewrite b as

functiontakingoneint b(int x, int y); 

from which, think, it's clearer type means.

hope helps!


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -