typedef union problem to compile

Help
2008-11-05
2013-03-12
  • Ronan CIMADURE
    Ronan CIMADURE
    2008-11-05

    Hi I'm frech so i'm not going to make a long text :
    I would like to use  a solution like this exemple  (i habit to use it)
    http://www.cppfrance.com/codes/CONVERSION-BINAIRE-DECIMAL-HEXADECIMAL-TRES-SIMPLE-DJGPP_10065.aspx
    in my code

    Goal passing 20 in KGITS .
    this is an short example,  in reality I have 16bits
    it's like
    //KMH_2DIGITS   = SpeedBAJA ;
    typedef union TWODIGITS {
    unsigned char decimal;
    struct {
                unsigned char dizaine:4;
                unsigned char unit:4;    };} ;
    TWODIGITS KGITS;
    KGITS.decimal =20;

    error : syntax error: token -> 'KGITS' ; column 15
    ---------------------------------------
    A trick :
    typedef union TWODIGITS {
    unsigned char decimal;
    struct {
                unsigned char dizaine:4;
                unsigned char unit:4;    };} KGITS ;
    SUCCES !!
    but When I add          KGITS .decimal = 20 ;
    error : syntax error: token -> '=' ; column 6

    SomeOne can Help me Please ( S'il vous plait Mr,Mme , Mselle )

     
    • Raphael Neider
      Raphael Neider
      2008-11-05

      Your typedef is useless:

      typedef union FOO {
        // whatever
      };

      defines an unnamed type as an alias for union FOO.

      You either need

      typedef union {
        // whatever
      } TWODIGITS;
      TWODIGITS KGITS;

      or

      union TWODIGITS {
        // whatever
      };
      union TWODIGITS KGITS;

      or (combining the type definition and the instantiation)

      union /*optional tag: TWODIGITS*/ {
        // whatever
      } KGITS;

      This problem is not sdcc specific but rather standard C (except for the anonymous struct).

      Hope that helps,
      Raphael

       
    • Raphael Neider
      Raphael Neider
      2008-11-05

      Oh, and the trick

      typedef union TWODIGITS {
        // whatever
      } KGITS ;

      defines KGITS to be an alias for the type 'union TWODIGITS'. As you cannot assign to types,
      KGITS.decimal = 20;
      must fail. You require an instance of the type to assign to:

      KGITS kgits;
      kgits.decimal = 20; // inside some function

      should work with your second typedef (of which the tag TWODIGITS would then be optional).

      Good luck,
      Raphael

       
    • Ronan CIMADURE
      Ronan CIMADURE
      2008-11-08

      Okkkkkkkkkkkk

      Now it's work , !!! THANKS Raphael
      Amazing , you reply in 20mins .

      Now i can start prompt digits :D