how to write a macro that calculate sizeof data types

M

Malcolm

sizeof will calculate the size of a data item or type. Just redefining it as
a macro will achieve nothing except to obfusucate your code. Ask what your
teacher is looking for here.
 
D

Dan Pop

Except for the trivial

#define SIZEOF sizeof

sizeof(type) cannot be replaced by a macro (portably). It would
have to use a trick similar to that used by the canonical offsetof
implementation (pointer arithmetic on a null pointer of the type
in question):

#define TSIZEOF(x) ((char *)((x *)0 + 1) - (char *)(x *)0)

What can be done portably is replacing sizeof lvalue by a macro:

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

Neither of these macros has the right type for sizeof, but this can be
trivially fixed.

The part that can't be implemented in standard C as a macro at all is
sizeof rvalue. This can be reduced to TSIZEOF with a GNU C extension:

#define RVSIZEOF(x) TSIZEOF(typeof(x))

Remeber: only LVSIZEOF is written in portable C, although TSIZEOF is
likely to work practically anywhere.

Dan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top