C program to implement your own sizeof using macro

Here, we are going to learn how to implement your own sizeof using macro in C programming language?
Submitted by Nidhi, on July 22, 2021

Problem Solution:

The sizeof is a unary operator in C/C++ programming language, it is used to get the occupied size of a variable, constant, expression, data type, etc. It returns an unsigned integral type (size_t).

Here, we will create a macro to implement own sizeof operator.


The source code to create own sizeof using a macro is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to create own sizeof using macro

#include <stdio.h>

#define MySizeOf(var) (char*)(&var + 1) - (char*)(&var)

int main()
    short num1 = 0;
    int num2 = 0;
    long num3 = 0;

    char ch = 0;

    printf("Size of num1: %ld\n", MySizeOf(num1));
    printf("Size of num2: %ld\n", MySizeOf(num2));
    printf("Size of num3: %ld\n", MySizeOf(num3));
    printf("Size of ch : %ld\n", MySizeOf(ch));

    return 0;


Size of num1: 2
Size of num2: 4
Size of num3: 8
Size of ch : 1


In the above program, we created four variables num1, num2, num3, and ch that are initialized with 0. And, we created a macro MySizeOf() to get the size of different types of variables. Then we printed the result on the console screen.

C Advance Programs »

Related Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.