Page 1 of 1

can we have variable with 2 datatypes

Posted: Fri Aug 13, 2004 2:33 am
by neopro
hi all,

can we declare a variable like int char a[];

is it possible. ...

any help greatly encouraged

Re:can we have variable with 2 datatypes

Posted: Fri Aug 13, 2004 3:16 am
by Legend
With basic types, no ...
As in: What should this be then?

Re:can we have variable with 2 datatypes

Posted: Fri Aug 13, 2004 3:17 am
by Candy
neopro wrote: hi all,

can we declare a variable like int char a[];

is it possible. ...

any help greatly encouraged

Code: Select all

union {
   char a[4];
   int b;
} variable;

variable.b = 0x12345678;
printf("%c", variable.a[2]); // prints 56 on big endian systems, 34 on little endian systems, Bus Error on some systems :D

Re:can we have variable with 2 datatypes

Posted: Fri Aug 13, 2004 8:28 am
by Legend
Yet this is a complex type! ;)

Re:can we have variable with 2 datatypes

Posted: Sat Aug 14, 2004 6:04 am
by Candy
Legend wrote: Yet this is a complex type! ;)
There is no way to define two non-complex types in one memory location. You can cheat your way out of it using complex pointers, but they're not easy either.

The union type has been created to make two things appear in one place, there's no way around it. BTW,

typedef union {
...
} new_type;

pretty much same as a normal type.

Re:can we have variable with 2 datatypes

Posted: Sat Aug 14, 2004 3:56 pm
by Schol-R-LEA
Perhaps a better question is, What are you trying to accomplish, and why do you think that this would be a solution to your problem? What is your goal in doing this?