Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular function pointer question in C

I am trying to figure out how to declare a function that returns a pointer to a function that returns a function. It's a circular problem and I don't know if this can be done in c. This is an illustrative example of what I'm trying to do (it does not work):

typedef (*)(void) (*fp)(void);

fp funkA(void) {
    return funkB;
}

fp funkB(void) {
    return funkA;
}
like image 205
Kenneth Avatar asked Jul 22 '11 07:07

Kenneth


People also ask

What is pointer in C programming?

Pointer is the solution to such problems. Using pointers, we can modify a local variable of a function inside another function. See the next question. Note that everything is passed by value in C. We only get the effect of pass by reference using pointers. Output of following program?

What is a null pointer in C?

Q) What is a NULL pointer? According to the C standard, an integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer is called a null pointer.

How do you declare a pointer to a function?

The declaration of a pointer to a function is similar to the declaration of a function. That means the function pointer also requires a return type, declaration name, and argument list.

What is circular queue in C?

Circular Queue in C | How Circular queue works in C? C Circular queue is defined as an implementation of the concept of the circular queue in C programming language in a practical manner.


1 Answers

To create completely circular types like this in C, you must use a struct (or union). In C99:

typedef struct fpc {
    struct fpc (*fp)(void);
} fpc;

fpc funkB(void);

fpc funkA(void) {
    return (fpc){ funkB };
}

fpc funkB(void) {
    return (fpc){ funkA };
}

In C89, you don't have compound literals, so you must do:

fpc funkA(void) {
    fpc rv = { funkB };
    return rv;
}

fpc funkB(void) {
    fpc rv = { funkA };
    return rv;    
}
like image 142
caf Avatar answered Sep 24 '22 10:09

caf