Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: Unnamed structs in C--bad?

Author: Dann Corbit

Date: 13:51:05 12/02/99

Go up one level in this thread


On December 02, 1999 at 16:21:48, Tom Kerrigan wrote:

>I'm currently using the following to define a move:
>
>typedef union {
>  int i;
>  struct {
>    char from;
>    char to;
>    char promote;
>    char flags;
>  };
>} move_t;
>
>This allows the structure to be treated as an integer, so moves can be copied
>and compared easily.
>
>However, I just noticed that VC++ 5.0 produces a level 4 warning because the
>struct is unnamed.
>
>How bad is this? Will some compilers not compile my stuff because of it?

Unnamed structs are a non-standard extension.  Some compilers won't compile it,
but most won't give you a problem.  There is an icky(tm) solution:
typedef struct {
    char from;
    char to;
    char promote;
    char flags;
} smove_t;

typedef union {
  int i;
  smove_t m;
} move_t;

typedef union {
  int i;
  struct {
    char from;
    char to;
    char promote;
    char flags;
  };
} bmove_t;

here, a move_t is fully standard, but you have to address a struct piece with
the prefix m to use it as the struct.  In the second case, a bmove_t is
non-standard but usage is more transparent.

Even more interesting is that there is no guarantee that the smove_t will fit
into an integer even if the integer is 4 bytes long (although it would be very
strange if it did not).  There are no restrictions on padding of structs defined
in the language definition [or even the physical ordering of the members!
That's why the offsetof() macro is needed].  Also, type int could be anywhere
from two to 8 octets on standard compilers currently in existance.

I think you will find that if the struct actually fits into an integer, then
operations on the struct will be about as efficient as operations on the int
(example -- exchange two items in an array).  It is possible that the union with
an int will force alignment restrictions that improve efficiency.



This page took 0 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.