ju**********@ya hoo.co.in wrote:
Hi,
Is it possible to implement sizeof as a C function ?
answer is no like others said but some code like below can fool you
thinking that mysizeof is similar to sizeof
#include<stdio. h>
#define str(x) #x
#define mysizeof(y) mysizeof1(str(y ))
int mysizeof1(char *s)
{
if(strcmp(s,"in t")==0) /* what ever the defined data types are
like long double etc */
return 1;
/* The compiler can do this because it stores the mapping
like a is associated with int ,as it scans the program but
* at runtime this information is lost/not known easily */
/* If you can find some way to associate a with type int or say
a mapping you can but i think at this stage it is too late because
promotions could have actually taken place or how would know what type
was passed to the function.
*/
return -1;
}
int main()
{
printf("%d\n",m ysizeof(int));
printf("%d\n",m ysizeof(a));/* i am going to get -1 here */
/* sizeof has lot of props like it doesn't evaluate the
experssion or the type . So you will have to take care of all that */
/* so what i will do on machines with CHAR_BIT 8 is a=0xFFFF;
now if sizeof(a) is 1, it will only contain FF, if sizeof(a) is 2 it
will contain FFFF, so on but this a very crude or wrong implementation
*/
return 0;
}
Probably you shouldn't be doing this but it is just for the sake of
curiousity and filled with lots of bugs
Question for others does this change for machines where CHAR_BIT is 9
or xyz.
If it is 0xFF on machines where CHAR_BIT is 8
a=0xFF;
should it be a=0x1FF on machines with CHAR_BIT 9
I think the latter but am little confused. Please clarify