What does , char *(*g(char a, int b)) mean?

Viewed 75

What does the following declaration mean?

char *(*g(char a, int b))

So far, I know that,

char *(*g)(char, int)

declares a pointer to a function that returns a char *, and I can successfully assign a value to it, however I can't do the same with the first. Any hints?

4 Answers

It looks like a function g that takes two arguments (char a and int b) and returns char**.

The outer parenthesis looks working like ones in char** x = /* some value */; char y = *(*x);

As a proof, this code compiles:

char *(*g(char a, int b));

char** test(void) {
    return g(0, 0);
}

The two lines of code in the question are very different:

char *(*g(char a, int b))  // #1

char *(*g)(char, int)      // #2

In #2 you have added a ) just after the g and that really changes the meaning a lot.

The first one is simply a function with the name g. It's the same as

char **g(char a, int b)   // #1 without the unnecessary ( ) pair

but number two is a function pointer variable with the name g.

That also explains why you can assign to g in case #2 but can't assign to g in case #1.

Also notice that #1 is a function returning pointer-to-pointer-to-char while #2 is a function-pointer to a function returning pointer-to-char

So the two lines of code are different in more than one aspect.

When you write :

char *(*g)(char, int);

g is a pointer to a function...

Is you've got several functions taking a character and an integer for parameters and returning a 'char *' you can assign either of these functions to this pointer..

Example :

char *function1(char c, int i) {
   ...
}

char *function2(char c, int i) {
...
}

when you declare a pointer like you can see below, it can point on either of the above functions :

char *(*g)(char, int);

You can write:

g = function1 ;

or:

g = function2 ;

And when you call the function using the pointer:

char *retVal = (*g)('a', 12) ;

It will call either function1 or function2 depending on the last function that was assigned to the pointer.

As for :

char *(*g(char a, int b)) 

This is equivalent to :

char **g(char a, int b) 

considering operator () has precedence level 1 and operator * has precedence level 2, the parenthesis doesn't affect the evaluation order.

Related