On trying to understand the functionality of container_of() from the source code linux kernel Definition of container_of, I found out that the below line in the definition of the macro looks like doing nothing.
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
So, I wrote a simple C program without the said line and tried to the compare the obtained results. Basically, I am trying to Understand how is the new implementation my_contianer_of() different from container_of() ? when both the implementation give same results.
#include <stdio.h>
#include <stddef.h>
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
#define my_container_of(ptr, type, member) ({ \
(char *)ptr - offsetof(type, member);})
struct container {
int *i;
char c;
float f;
};
void foo(char *cptr)
{
printf("foo : %p\n", my_container_of(cptr, struct container, c));
}
int main(int argc, char *argv[])
{
struct container tc;
printf("&tc : %p\n", &tc);
printf("cof : %p\n", container_of(&tc.c, struct container, c));
printf("mycof: %p\n", my_container_of(&tc.c, struct container, c));
foo(&tc.c);
return 0;
}
The below is the sample output for the above c program.
&tc : 0x7ffca543e0c0
cof : 0x7ffca543e0c0
mycof: 0x7ffca543e0c0
foo : 0x7ffca543e0c0
Please don't mark this question as the duplicate of any other question or this Understanding container_of macro in the linux kernel as those questions did not provide the required answer for my query.