Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation of sizeof operator

I have tried implementing the sizeof operator. I have done in this way:

#define my_sizeof(x) ((&x + 1) - &x) 

But it always ended up in giving the result as '1' for either of the data type.

I have then googled it, and I found the following code:

#define my_size(x) ((char *)(&x + 1) - (char *)&x) 

And the code is working if it is typecasted, I don't understand why. This code is also PADDING a STRUCTURE perfectly.

It is also working for:

#define my_sizeof(x) (unsigned int)(&x + 1) - (unsigned int)(&x) 

Can anyone please explain how is it working if typecasted?

like image 740
Raghu Srikanth Reddy Avatar asked Jan 05 '13 11:01

Raghu Srikanth Reddy


People also ask

How sizeof is implemented?

To use the sizeof(), we can take the value using a variable x, using &x, it will print the address of it. Now if we increase the value of &x then it may increase in different way. If only one byte is increased, that means it is character, if the increased value is 4, then it is int or float and so on.

How sizeof operator works in C?

It is a compile-time unary operator and used to compute the size of its operand. It returns the size of a variable. It can be applied to any data type, float type, pointer type variables. When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type.

What is the use of sizeof () operator?

You can use the sizeof operator to determine the size that a data type represents. For example: sizeof(int); The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding.

What is the use of sizeof () operator in C ++? Give an example?

The sizeof() operator in C gives the size of its operand at compile time. It does not evaluate its operand. For example, int ar1[10]; sizeof(ar1) // output 40=10*4 sizeof(ar1[-1]) // output 4 int ar2[ sizeof(ar1) ]; // generate an array of 40 ints.


1 Answers

The result of pointer subtraction is in elements and not in bytes. Thus the first expression evaluates to 1 by definition.

This aside, you really ought to use parentheses in macros:

#define my_sizeof(x) ((&x + 1) - &x) #define my_sizeof(x) ((char *)(&x + 1) - (char *)&x) 

Otherwise attempting to use my_sizeof() in an expression can lead to errors.

like image 110
NPE Avatar answered Sep 28 '22 10:09

NPE