[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [avr-gcc-list] Problem with union
From: |
Theodore A. Roth |
Subject: |
Re: [avr-gcc-list] Problem with union |
Date: |
Mon, 23 Aug 2004 16:14:52 -0700 (PDT) |
On Tue, 24 Aug 2004, Eric Fu wrote:
> Ned Konz Wrote:
>
> > Probably used #define for the definition of 'word' , instead of a typedef
> like
> > you should have done.
> >
> > Using the standard typedefs, your code compiles just fine:
> >
> > // avr-gcc -mmcu=atmega16 -Wall xx2.c
> >
> > #include <inttypes.h>
> > #include <avr/io.h>
> >
> > typedef union TwoBytes
> > { /* unsigned 16 bit type for 8 & 16 */
> > uint16_t wForm; /* bit accesses: 16 bit var.wForm */
> > struct
> > { /* 8 bit var.byForm.High/Low */
> > uint8_t High;
> > uint8_t Low;
> > } byForm;
> > } TwoBytes;
> >
> >
> > int main(int argc, char const * const * argv)
> > {
> > TwoBytes ThisNodeID;
> >
> > ThisNodeID.wForm = 1;
> >
> > return 0;
> > }
> >
> > --
> > Ned Konz
> > http://bike-nomad.com
> >
>
> Hi Ned,
>
> I did "typedef unsigned short word;" in another header file which was
> included. Your suggestion prompted me to put
> " ThisNodeID.wForm = 1; " inside a function. (I previously initialised
> ThisNodeID.wForm outside a function). And now it works fine.
> However, I initialised an unsigned char when I defined it outside any
> functions and the compiler doesn't complain and it seems working fine. DO I
> have to initialise a union inside a function only, while I can do it outside
> any function for other global variables?
>
> Thanks for help.
You can do that initialization outside of a function, but you'd have to
do it like this:
TwoBytes ThisNodeID = { 1 };
or more explicitly, like this:
TwoBytes ThisNodeID = { .wForm = 1 };
What you did with
ThisNodeID.wForm = 1;
is not really an initialization, but an assignment operation and you
can't do operations outside of a function in C, thus the compiler
warning (the real C gurus on the list can correct me if my understanding
of this is deficient).
---
Ted Roth
PGP Key ID: 0x18F846E9
Jabber ID: address@hidden