Functions as Structure Members

A programming puzzle kept me awake one night: If a structure allows for any variable type to be a member, and a function is a valid variable type, why not have a structure with a function as one of its members? Am I nuts?

Yes, I’m nuts.

Referring back to a Lesson from 2015, functions are variables. All you must do is declare them properly — type (*name)(arguments) — and you can have a function as a member in a structure.

Never mind the why, though I can think of some intriguing reasons, but here is such a structure definition:

struct f {
    void (*f1)();
    void (*f2)();
};

Structure f contains two functions as members, f1 and f2. Like any structure definition, these members are placeholders. The next step is to declare a struct f variable and then assign functions to the f1 and f2 members. The following code demonstrates:

#include <stdio.h>

void left(void)
{
    puts("left");
}

void right(void)
{
    puts("right");
}

int main()
{
    struct f {
        void (*f1)();
        void (*f2)();
    };
    struct f func;

    func.f1 = &left;
    func.f2 = &right;

    func.f1();
    func.f2();

    return(0);
}

The silly functions left() and right() output strings. These functions are assigned to the members f1 and f2 of struct f variable func at Lines 21 and 22. Only the functions’ names are used, prefixed by the address-of (& ampersand) operator. Remember that functions are referenced internally by their addresses.

At Lines 24 and 25, the functions are called — indirectly via the structure members:

func.f1();
func.f2();

And it works! Here’s the output:

left
right

Keeping in mind that a structure is yet another type of C language variable (I refer to is as a “multi-variable” in my books), the potential of mixing data with functions is nifty. In a way, it opens a portal through which you could create almost object-oriented like features in the C language: By attaching functions to a data type, you can access them similar to the way “methods” are accessed in object-oriented languages. Of course, a lot of overhead would be involved, but the potential exists.

5 thoughts on “Functions as Structure Members

  1. Pretty cool.

    One of my programming buddies from way back when mentioned on LinkedIn that this is how they implemented OOP in C before C++ and Objective C.

  2. I only wrote that article because, like you, I wondered whether it was possible. I wonder how often people have done something similar in production code and whether there are any examples floating around.
    Before Simula, the first real OOP language, I have heard people used object-oriented techniques in non-OO languages, probably FORTRAN or whatever, presumably using similar methods.

Leave a Reply