On 26 Mar 2007 06:14:28 -0700, "ramana" <
[email protected]>
wrote in comp.lang.c:
Do not top post in this group, it is considered rude. Text you add
should be after or interspersed with quoted text you are responding
to. I have reformatted your post and added my comments.
Yes it's possible to know. use this macro
#define SIZE(x) ( ((char*)(&x + 1)) - (char*)&(x) )
where 'x' is the variable.
sample.c:
.....................
#include <stdio.h>
#define SIZE(x) ( ((char*)(&x + 1)) - (char*)&(x) )
The macro is correct.
int main()
{
char c;
int i;
float f;
double d;
printf(" sizes of char = %d \t int = %d \t float = %d \t double = %d
\n", SIZE(c), SIZE(i), SIZE(f), SIZE(d));
The printf() statement above is non-portable at best, and causes
undefined behavior at worst. The subtraction of two pointers yields a
result with a type of ptrdiff_t, which is a signed integer type but
not necessarily a signed int.
If ptrdiff_t happens to be signed int on your implementation, or
signed short (unlikely!), then the code will do what you want.
On implementations where ptrdiff_t is a wider type than int, and I
work with some, the code produces undefined behavior.
The obvious solution is to add a cast to int in your macro. Less
obvious but slightly better is to add a cast to long, and change the
conversion specifiers to %ld.
Best, of course, is get rid of the macro and use sizeof.
return 0;
}
.............................
Kindly learn how to post a proper signature line. It is separated
from the body of your message by the character string "-- " appearing
on a line by themselves. See my signature below for an example.
--
Jack Klein
Home:
http://JK-Technology.Com
FAQs for
comp.lang.c
http://c-faq.com/
comp.lang.c++
http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html