C provides a compile-time unary operator called sizeof
that can be used to compute the size of any object. The sizeof
operator can be used in two forms. First, to get size of an object that can be a variable or array or structure. Second, to get size of a type name that can be the name of a basic type like int
or double
, or a derived type like a structure or a pointer. The following expressions shows the syntax of sizeof
sizeof (object);and
sizeof (type name);
The sizeof
operator yields an integer equal to the size of the specified object or type in bytes. (Strictly, sizeof
produces an unsigned integer value whose type, size_t
, is defined in the header <stddef.h>.)
A sizeof
cannot be used in a #if
directive, because the preprocessor does not parse type names. But sizeof
in the #define
is not evaluated by the preprocessor, so the code here is legal.
Now come to implementation of the sizeof
operator. The sizeof
in C is an operator, and all operators have been implemented at compiler level; therefore, you cannot implement sizeof
operator in standard C as a macro or function. You can do a trick to get the size of a variable by pointer arithmetic. However, pointer arithmetic underneath uses the sizeof
operator to figure out the size of the type in order to increment or decrement the pointer to point either next or previous object location.
The following C program develops a small macro SIZEOF() that replicates the functioning of sizeof
when used to get size of variables.
#include <stdio.h> #define SIZEOF(object) (char *)(&object+1) - (char *)(&object) int main() { double x; int arr[10]; printf("double var size: %d\n", SIZEOF(x)); printf("double type size: %d\n", sizeof(double)); printf("int arr[10] size : %d\n", SIZEOF(arr)); return 0; } OUTPUT ====== double var size: 8 double type size: 8 int arr[10] size : 40
The above macro implementation of SIZEOF
won't work for SIZEOF(double)
because the argument passed to SIZEOF
must be a variable, not a type. Following is a silly trick which first creates a variable of given type then calls SIZEOF
with that variable, but this is not a feasible and fool proof solution. You cannot call DECLARE_TYPE
two times, second time it will through error saying "redeclaration of newvar
".
#include <stdio.h> #define SIZEOF(object) (char *)(&object+1) - (char *)(&object) #define DECLARE_TYPE(type) __typeof__(type) newvar int main() { double x; int arr[10]; printf("double var size: %d\n", SIZEOF(x)); printf("double type size: %d\n", sizeof(double)); printf("int arr[10] size : %d\n", SIZEOF(arr)); DECLARE_TYPE(double); printf("double type size: %d\n", SIZEOF(newvar)); return 0; } OUTPUT ====== double var size: 8 double type size: 8 int arr[10] size : 40 double type size: 8
Hope you have enjoyed reading the C program implementing sizeof
operator using macro. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!
Share this page on WhatsApp