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.

Program:

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;
}

Output:

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

Explanation:

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

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.