Page 1 of 1

unions?

Posted: 16 Dec 2009 15:09
by peterverkaik
I tried out the new MikroC PRO for dsPIC
and there we can declare unions (same area of memory occupied
by different datatypes).

I could not find 'union' for MikroE Basic PRO for dsPIC, only structure.

Are unions supported, or will they, or is there a workaround
to implement unions?

regards peter

Posted: 17 Dec 2009 11:17
by anikolic
Hi,
As far as I know there are no unions in Basic language standard, only structures. Unions are C-specific and this is one of the major reasons why some mikroC compiled libraries (.MCL) that use unions cannot be used in mikroBasic.

Best regards,
Aleksandar

Posted: 19 Dec 2009 22:10
by extrapilot
Peter
As I recall, you can emulate unions in MB by using absolute addressing for a series of variables or structures (such that they overlap).
Regards,
Rob

Posted: 20 Dec 2009 01:08
by janni
Actually, it's no longer necessary to use the directive absolute. One may use the keyword at to emulate a union in mB.
Here's an example:

Code: Select all

typedef Tunion as byte[4]

dim union as Tunion

dim union_x as float at union
dim union_w as word at union
dim union_b as byte at union

main:
  union_b=1
  union_w=256
  union_x=1.0
All three variables will operate on the same space in RAM (though obviously, the byte variable will need just one byte, the word variable - 2, and the float one will use all space - 4 bytes).

Naturally, one may also declare a pointer to such 'union'

Code: Select all

dim Uptr as ^Tunion

  Uptr=@union

Posted: 20 Dec 2009 01:26
by janni
A thought - if the (overworked :( ) developers at mE had some time, compiler could properly interpret following declaration

Code: Select all

structure my_union
  dim x as float
  dim w as word at x
  dim b as byte at x
end structure
and we would have unions in mB without naming them as such :wink: .

Posted: 20 Dec 2009 11:06
by Skyline
Hi Janni,

Thank you much for your elaboration of the at keyword to emulate unions in MB instead of absolute, your pointers are really nice.

Thanks again for the help you have been providing.

Posted: 20 Dec 2009 14:48
by peterverkaik
My workaround for now is to declare structures of equal size
but different members. Then use a pointer, casted to particular
structure pointer, to access members. That works well.

Since C PRO for dsPIC already implements unions including bitfields,
I see no reason why Basic PRO should not have unions, even if it
is a non-standard basic extension. In fact, it could increase sales
but if you now want unions you could use the free C30 instead
of mE C PRO. Having unions in Basic could make people to select
mE Basic PRO.

regards peter