Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof- function or macro? [duplicate]

Tags:

c

sizeof

In c, we are using the sizeof() for getting the size of the datatypes. So how it is defined. It is a macro or a function.

Because we can use that as two ways,

sizeof int

and

sizeof(int)

so how this is defined in header file.

like image 636
Karthikeyan.R.S Avatar asked Feb 28 '26 23:02

Karthikeyan.R.S


2 Answers

It's neither. It's a built-in operator, whose value is computed at compile-time unless the argument is the name of a variable-length array (added in C99).

The parentheses that you often see are not part of the "call", since sizeof is not a function. They are part of the argument, and are only needed when the argument is a cast expression, i.e. the name of a type enclosed in parentheses.

I personally recommend against using sizeof with a type name as the argument whenever possible, since it's usually not needed, and creates a disconnect/de-coupling which can lead to errors.

Consider something like this:

float *vector = malloc(100 * sizeof(double));

The above, of course, contains a bug: if float is smaller than double, it will waste a lot of memory. It's easy to imagine ending up with something like the above, if vector started out as an array of double but was later changed to float. To protect aginst this, I always write:

float *vector = malloc(10 * sizeof *vector);

The above uses the argument *vector (an expression of type float) to sizeof, which is not a type name so no parentheses are needed. It also "locks" the size of the element to the pointer used to hold it, which is safer.

like image 111
unwind Avatar answered Mar 02 '26 14:03

unwind


Sizeof is neither a macro nor a function.Its a operator which is evaluated at compile time.

Macros evaluated during pr-processing phase.

As pointed out by @Yu Hao Variable length arrays is the only exception.

For More Understanding solve this;

#include<stdio.h>
    char func(char x)
    {
           x++;
           return x;
    }

    int main()
    {
           printf("%zu", sizeof(func(3))); 
                return 0;
    }

    A) 1            B)2             C)3     D)4
like image 24
Vagish Avatar answered Mar 02 '26 14:03

Vagish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!