Friday, June 15, 2018

C Language : Write you own sizeof operator and container_of macro

#include<stdio.h>

/* #define SIZEOF(ptr)   ((char *)(&ptr+1) - (char *)(&ptr)) */

#define SIZEOF(t)  ((char *)(((typeof(t) *)0) + 1) - (char *)0)

int main()
{
        int val =1;

        printf("SIZEOF is %d\n", SIZEOF(int));

        return 0;
}

Note the typeof operator. A non-standard operator generally supported by gcc compilers.This is part of gcc compiler extension. Also this programs works for all cases like sizeof(int). I dont think this program can be written using standard C keywords.

The container_of macro :-

#define container_of(ptr, type, member) ({                      \
        const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
        (type *)( (char *)__mptr - offsetof(type,member) );})
(type *)( (char *)__mptr - offsetof(type,member) );})

No comments:

Post a Comment