0

I am trying to define a structure in C for a square where each side can either have a given color (labeled by int) or not have any color at all.

I would like my struct to behave like a named tuple, i.e allow for referring to the north color by square.n = 0; or square.c[NORTH_DIRECTION] = 0; interchangeably.

Is the following a correct way to do it:

typedef struct {
  union {
    struct {
      int n, e, s, w;
    };
    int c[4];
  };
  union {
    struct {
      bool n_is_null, e_is_null, s_is_null, w_is_null;
    };
    bool is_null[4];
  };
} SquareColors;

Thank you very much!

Cosmo Sterin
  • 171
  • 8
  • Why not just use `0` as a value for "no color"? The use of a `union` here seems fine, but I wouldn't use two of them. – Cheatah Apr 09 '22 at 22:42
  • This struct is used in a mathematical context where 0 is a valid and useful color to have. So do any int. However it seems that this union/struct approach is dangerous because of padding inside the struct: https://stackoverflow.com/questions/47471398/how-does-padding-of-structs-inside-unions-work – Cosmo Sterin Apr 09 '22 at 22:45
  • The way that unions work is by recognizing that values can be type-punned. In this case, the underlying precondition is that x_is_null does not share values with a valid color. So... skip the booleans and just use an invalid color value for “no color”. – Dúthomhas Apr 09 '22 at 22:56
  • There is no valid choice for an invalid color value in the model I work with. – Cosmo Sterin Apr 09 '22 at 22:57
  • Can you use `-ve` values for indicating `no-colour`? – जलजनक Apr 09 '22 at 23:04
  • Unfortunately no because negative colors have a valid meaning in this model (imagine its some kind of physical model). Note that my main point was moreso about how to portably define named tuples in C11 and it looks that this is not the way because of https://stackoverflow.com/questions/47471398/how-does-padding-of-structs-inside-unions-work – Cosmo Sterin Apr 09 '22 at 23:07
  • An alternative is to remove the inner struct and union and do: `#define n c[NORTH_DIRECTION]` (e.g.). It works fine if you're careful with the names. But maybe shortening the names is better and just use (e.g.) `c[N]` everywhere? – Craig Estey Apr 10 '22 at 02:14

0 Answers0