loading...

Passing a function to a structure in C

twitter logo github logo ・1 min read

I was wondering if there was any way I could pass a function to a structure in C, I've looked up my inquiry, but all I got was:


How to pass a Structure to a function


So, is there any way to do the reverse, such as:

#include <stdio.h>

/* I know this won't work, but this is an example of what I want */
struct Test {
    function func;
};

int tfunc() {
    return 1;
}

int main() {
    struct Test c = {tfunc};
    return 0;
}

Thanks!
Cheers!

twitter logo DISCUSS (8)
markdown guide
 

Use int (*func)();

Pointer to function that returns an int

 

I want to assign the variable to the function itself...
e.g.:

structure.function()
 

Ok, but I need to cast a datatype, and I don't know if I made this clear (which I'm sorry about...), I was trying to ask, what datatype to I need to cast to assign something to a function, i.e. a struct member,
because the casting types, as far as I know of, are:

int
struct
char
void // Only in the case of functions returning nothing
// Other datatypes

though you didn't provide a casting type.....

struct Test {
    int (*func)();
};

int tfunc() {
    return 1;
}

int main() {
    struct Test c = {tfunc};

    // call here
    int result = c.func();
    return 0;
}
 
Classic DEV Post from May 10 '19

Why I ignore the hype (and you should too)

It’s been 20 years since I made my first website. I've been burned by the hype ti...

PDS OWNER CALIN (Calin Baenen) profile image
I am a 13 (as of Oct 30 of 2019) yr/o developer (I have been developing mini-projects for 4, years now, since I was 9), who makes projects in languages like: Java, HTML, Python 3, JS, CSS, and C#.