can we have variable with 2 datatypes

Programming, for all ages and all languages.
Post Reply
neopro

can we have variable with 2 datatypes

Post by neopro »

hi all,

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

is it possible. ...

any help greatly encouraged
Legend

Re:can we have variable with 2 datatypes

Post by Legend »

With basic types, no ...
As in: What should this be then?
User avatar
Candy
Member
Member
Posts: 3882
Joined: Tue Oct 17, 2006 11:33 pm
Location: Eindhoven

Re:can we have variable with 2 datatypes

Post 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
Legend

Re:can we have variable with 2 datatypes

Post by Legend »

Yet this is a complex type! ;)
User avatar
Candy
Member
Member
Posts: 3882
Joined: Tue Oct 17, 2006 11:33 pm
Location: Eindhoven

Re:can we have variable with 2 datatypes

Post 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.
Schol-R-LEA

Re:can we have variable with 2 datatypes

Post 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?
Post Reply