Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding a typedef in c [duplicate]

Tags:

c

typedef

I've been reading a c code here. I don't understand this typedef:

typedef const char * (*Responder)( int p1);

Is p1 a parameter of Responder? Is Responder a const char?

like image 211
bigTree Avatar asked Feb 02 '26 05:02

bigTree


2 Answers

typedef is (syntactically) nothing else than any other storage-class specifier (like static or extern), just think about what this would declare without the typedef:

const char * (*Responder)( int p1);

Responder is a pointer to a function (getting an int) returning a pointer to const char.

So, with the typedef, you have:

Responder is a type synonym for a pointer to a function (getting an int) returning a pointer to const char.

Related: http://c-faq.com/decl/spiral.anderson.html

HTH

like image 186
mafso Avatar answered Feb 05 '26 03:02

mafso


Using typedef with a function pointer is definitely doable, as shown here and here.

For example (from one of the links):

int do_math(float arg1, int arg2) {
    return arg2;
}

int call_a_func(int (*call_this)(float, int)) {
    int output = call_this(5.5, 7);
    return output;
}



int final_result = call_a_func(&do_math);

This code can be rewritten with a typedef as follows:

typedef int (*MathFunc)(float, int);

int do_math(float arg1, int arg2) {
    return arg2;
}

int call_a_func(MathFunc call_this) {
    int output = call_this(5.5, 7);
    return output;
}

int final_result = call_a_func(&do_math);

In your specific case, it's a pointer to a function called Responder that returns a char * and takes an int as an argument.

like image 31
Ricky Mutschlechner Avatar answered Feb 05 '26 03:02

Ricky Mutschlechner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!