简体   繁体   中英

C structs using self

I have some code that a program generated for me, and I really do not understand why it does what it does. The language is plain C, and a struct is generated.

.h-file:

struct X_IMPL {
   sint32 y;
};

struct X {
   struct X_IMPL * IMPL;
};

.c-file:

#define _my_y self->IMPL->y

sint32 do_something(struct X * self)
{
    return _my_y*13;
}

I do assume that _my_y now points to a variable inside the struct, and can be used to change the struct's variable. My question is, why would code be generated this way? Is there any advantage compared to just simply using the parameter's reference? When a reference is created with a define like that, do I really need that parameter at all?

I think what you are seeing is "object oriented programming" in C. Note that it's not usually 1:1 equivalent to OOP in C++/Java/C#/whatever, because the OOP mechanisms are not built-in, but implemented explicitly. So different projects and different developers might write quite different code for same thing, while in some other language with built-in OOP features, they'd all just use the built-in features the same way.

The do_something in C++ might look like this:

// do_something is public member function AKA method of class X
sint32 X::do_something()
{
    // y is this->y, private member variable of class X
    return y * 13; 
}

It is just a matter of preferences, as you can do that in many ways, this one is not that sheer. On the first line, where the define is, it assigns nothing but define a macro for accessing a struct pointer through a struct pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM