LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   sizeof operator implementation (https://www.linuxquestions.org/questions/programming-9/sizeof-operator-implementation-247459/)

vinods 10-26-2004 08:57 AM

sizeof operator implementation
 
Dear Memebers,

I want to know how exactly the sizeof Operator is implemented in C?

In the thread id 236101 it is explained that the sizeof operator is implemented as follows:

#define sizeof(x) ((void *)(&x + 1) - (void *)(&x))

This will give the correct output when we pass a variable as a parameter, as explained in the following code

#include <stdio.h>
#define sizeof(x) ((void *)(&x + 1) - (void *)(&x))
void main()
{
int a;
printf("int size=%d",sizeof(a));
}
Output will be
int size=4



But it will fail to compile when we pass the data type as a parameter, as shown in the following code

#include <stdio.h>
#define sizeof(x) ((void *)(&x + 1) - (void *)(&x))
void main()
{
printf("int size=%d",sizeof(int));
}

And also as far as my knowledge goes the sizeof operator will be evaluated at the compile time and will be replaced by an integer value before the actual code generation. The above sizeof defination when works will give the value only at run time.

Someone please help me.

Thanks,

Regards,
Vinod.

itsme86 10-26-2004 09:57 AM

sizeof is a unary operator. It's not in a header file or library, it's part of the compiler just like - or ! are.


All times are GMT -5. The time now is 04:28 AM.