Saturday, July 14, 2012

pointerception in C

This is something that I still have a hard time, so I'll leave here two clear explanations from stackoverflow user Charles Bailey

c++ - Spiral rule and 'declaration follows usage' for parsing C expressions - Stack Overflow
You just have to build it up in steps.
char *X();  // X =~ (*(*a[N])())
Function returning char*
char *(*Y())();  // Y =~ (*a[N])
Function returning pointer to function returning char*.
In a declaration, just as in an expression (declaration follow usage), postfix [] has a higher precedence that unary * so *a[N] is equivalent to *(a[N]), not (*a)[N].
char *(*(*Z)())();  // Z =~ a[N]
Pointer to function returning pointer to function returning char*.
char *(*(*a[N])())();
Array of N pointers to functions returning a pointer to function returning char*.
c - what's the meaning of this piece of code? void (signal(int sig, void (func)(int)))(int); - Stack Overflow
#include <signal.h>
void (*signal(int sig, void (*func)(int)))(int);
It's the declaration of a function taking an int and a pointer to a function (taking int returning void) and returning a pointer to a function (taking int and returning void).

Explanation, or guide to interpretation

You can interpret by treating everything in parentheses as a single entity and then working inwards using the "declaration follows usage" rule.

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

The entity in the brackets looks like a function taking int and returning void.

Stripping away the outer part:
*signal(int sig, void (*func)(int))

So, signal takes some parameters and returns something that can be dereferenced (due to the leading *) to form a function taking int and returning void.

This means signal is a function returning a pointer to a function (taking int and returning void).
Looking at the parameters it takes an int (i.e. sig) and void (*func)(int) which is a pointer to a function (taking int and returning void).
The guy deserves the 128 thousand points of reputation.

No comments:

Post a Comment

Before writing, please read carefully my policy for comments. Some comments may be deleted.

Please do not include links to commercial or unrelated sites in your comment or signature, or I'll flag it as SPAM.

LinkWithin

Related Posts with Thumbnails