Suppose you have the following struct:
struct Object {
int field;
}
In C, there is no good way to write object.Add(1)
and make Add
use/change fields of object
. You have two options:
a) Abandon the wish to write object.Add(1)
and write idiomatic C code instead. Trying to find a way to write object.Add(1)
in C using some tricks will just make the code more complex, more bug prone, and is not worth it.
The equivalent way to do it in C is to have a separate function accept a pointer to the object:
void Add(struct Object *object, int amount) {
object->field += amount;
}
And call this function as follows:
struct Object object;
Add(&object, 1);
b) Use another programming language. For example, in C++, you can define a method:
struct Object {
int field;
void Add(int amount) {
field += amount;
}
}
and use it in your code:
Object object;
object.add(1);
The C++ compiler will make it work on your behalf. In fact, as long as inheritance is not involved, the C++ code will be equivalent to the function definition and its invocation mentioned in (a).