Thread: Structure Vs Union

  1. #16
    Registered User
    Join Date
    Sep 2008
    Toronto, Canada
    Good point. I was just pointing out that most people would not consider a struct to be a basic data type that's unionable in this context.

    From now on I will assume all the people cursing me are secretly impressed! I'll enjoy life more that way.

  2. #17
    Registered User
    Join Date
    Oct 2001
    Quote Originally Posted by nonoob View Post
    I don't see it as cheating doing this.
    Sure it's not cheating, but it is undefined behavior in ISO standard C. You could use compiler extensions like GCC has to get the behavior you want, though.

  3. #18
    Registered User
    Join Date
    Oct 2001
    Ok, seems I'm wrong somewhat. in N1256 (a post-C99 draft), there's footnote 82 which says:
    If the member used to access the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the newtype as described in 6.2.6 (a process sometimes called "type punning"). This might be a trap representation.
    So it appears to be valid, as long as the accessed value isn't a trap representation in the type you're using to access the object. Since unsigned chars don't trap, you could determine endianess this way, like nonoob said, I think.

    Also, there's a completely different part that condones the use of accessing similar structs in a union:
    Quote Originally Posted by
    One special guarantee is made in order to simplify the use of unions: if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the complete type of the union is visible. Two structures share a common initial sequence if corresponding members have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.
    Note that this depends on whether or not the definition of the union is visible, which wouldn't be hard in most circumstances, I guess.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 05-18-2010, 04:14 AM
  2. Problem Passing Structure Reference To Function
    By soj0mq3 in forum C Programming
    Replies: 9
    Last Post: 04-24-2010, 10:27 AM
  3. union inside structure
    By vijay s in forum C Programming
    Replies: 1
    Last Post: 12-03-2009, 07:21 AM
  4. structure and union
    By BEN10 in forum C Programming
    Replies: 10
    Last Post: 06-24-2009, 11:30 PM
  5. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM