0

I'm aware of what container_of macro does, but I'm far from understanding it.

I know one can get a struct reference as long as having its member's name, member's type, and member's reference.

For example, consider the code below

struct car //car is one of many kind of vehicles
{
    struct vehicle base; //vehicle is anything that moves you.
    /*other attributes that car has*/
};

int do_something(struct vehicle* a_vehicle)
{
    struct car* a_car = container_of(a_vehicle, struct car, base);
    /*do some operations*/
}

The function do_something() can be treated as a method operating on vehicle object. However, inside the function what really happen is opposite to its name. In other words, the real object being operated on is car, not vehicle.

Why cannot just pass struct car?

What would do_something() be like if container_of was not allowed to use?

  • 1
    C++ language is derived from C + C preprocessor. Read the history and technical details of the very first versions of the C++ compiler. You will find the answer to your question. Other qustions are related to OOP paradigm. I highly recommend reading books. – 0andriy Mar 15 '22 at 09:44
  • Also `container_of` isn't standard C, it boils down to non-standard gcc extensions like `typeof`. If you are looking for advise how to proper C programming, the Linux kernel is probably the very last place you should look. – Lundin Mar 15 '22 at 12:04
  • @Lundin It is possible to define `container_of` without using `typeof`. For example `#define container_of(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member)))`. – Ian Abbott Mar 15 '22 at 15:52
  • For the code given in the question where `base` is the first member of `struct car`, a simple cast operation can be used: `struct car* a_car = (struct car*)vehicle;`. – Ian Abbott Mar 15 '22 at 16:19
  • Thanks for all your feedback. It seems like `container_of` only offers syntax sugar? I thought it would be having other benefits on other aspect, such like encapsulation or inheritance. – Mr.nerd3345678 Mar 16 '22 at 01:42

0 Answers0