HomeAbout UsContact Us

Custom sizeof operator in C

By Jithin Tom
Published in Embedded C/C++
September 22, 2022
1 min read
Custom sizeof operator in C

The unary operator ‘sizeof’ is a very handy tool in C as well as in C++. It gives the storage size of a data-type/variable. This article describes an example C program showing the custom implementation of the ‘sizeof’ operator using macros.

#include <stdio.h>
#include <stddef.h>
#define MYSIZEOF(X) ((size_t)((char *)(&(X) + 1) - (char *)(&(X))))
int main(void)
{
int x;
printf("%zu\n", MYSIZEOF(x));
return 0;
}

This example is an implementation of a custom sizeof() operator in C. The sizeof() operator functionality is implemented here using the macro function MYSIZEOF().

Description

The code section, (char )(&(X) + 1)* adds 1 to the pointer according to the pointer type and the resultant address is type-casted to a character pointer. Correlating with the example, when the address of the integer variable x is added with 1 then the address is advanced by 4 bytes (considering 4 bytes for int). In the right hand side of the - operator, the address of the variable is type-casted to a character pointer.

Now the expression ((char )(&(X) + 1) - (char )(&(X))) gives the size of the variable.

Frequently Asked Questions

How can you implement a custom `sizeof` replacement in C?

By using pointer arithmetic with macros. For example, `#define my_sizeof(type) ((char *)(&type + 1) - (char *)(&type))`. This calculates the byte difference between pointers to adjacent objects.

Why does subtracting char pointers yield the correct size in bytes?

In C, `char` is guaranteed to be 1 byte. Casting pointers to `char*` before subtraction forces the compiler to return the distance between the two addresses in individual bytes.

Why should you prefer the built-in `sizeof` operator over custom macros?

The built-in `sizeof` operator is evaluated at compile time and is a key language feature. Custom macros using address-of operators (`&`) cannot be used on register variables or temporary expressions.

Tags

#c#embedded#sizeof

Share


Previous Article
C program to reverse a string
Jithin Tom

Jithin Tom

A Closer Look at C/C++, RTOS, and Embedded Systems

Related Posts

Implementation of Singly Linked List in C
Implementation of Singly Linked List in C
September 22, 2022
2 min
© 2026, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media