C Structs – Can They Behave Like Functions?

cdata structuresobject-oriented

I use C and structs where a struct can have members but not functions. Assume for simplicity that I want to create a struct for strings that I name str and I want to be able to do str.replace(int i, char c) where i is the index of the string and c is the character to replace the character at position i. Would this never be possible since structs can't have functions or is there still some way we can implement this behavior and mimic that a struct could have a (simple) function that actually only is the struct copying itself to a new struct and updating its fields, which it could do?

So replace could be a third member of the struct that points to a new struct that is updated when it is accessed or similar. Could it be done? Or is there something builtin or some theory or paradigm that prevents my intention?

The background is that I'm writing C code and I find myself reinventing functions that I know are library builtins in OOP languages and that OOP would be a good way to manipulate strings and commands.

Best Answer

Your function should look like this.

void
replace(struct string * s, int i, char c);

This accepts a pointer to the object to operate on as the first parameter. In C++, this is known as the this-pointer and need not be declared explicitly. (Contrast this to Python where it has to.)

In order to call your function, you would also pass that pointer explicitly. Basically, you trade the o.f(…) syntax for the f(&o, …) syntax. Not a big deal.

The story becomes more involved if you want to support polymorphism (aka virtual functions). It can also be emulated in C (I've shown it for this answer.) but it ain't pretty to do by hand.

As Jan Hudec has commented, you should also make it a habit to prefix the function name with the type name (ie string_replace) because C has no name-spaces so there can only be a single function named replace.

Related Topic