Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between struct { ... } and struct { union { struct { ... } } }?

Is there a reason why DISK_DETECTION_INFO is defined as

typedef struct _DISK_DETECTION_INFO {
  DWORD          SizeOfDetectInfo;
  DETECTION_TYPE DetectionType;
  union {
    struct {
      DISK_INT13_INFO    Int13;
      DISK_EX_INT13_INFO ExInt13;
    };
  };
} DISK_DETECTION_INFO, *PDISK_DETECTION_INFO;

instead of

typedef struct _DISK_DETECTION_INFO {
  DWORD          SizeOfDetectInfo;
  DETECTION_TYPE DetectionType;
  DISK_INT13_INFO    Int13;
  DISK_EX_INT13_INFO ExInt13;
} DISK_DETECTION_INFO, *PDISK_DETECTION_INFO;

or am I just overanalyzing this piece of code?

like image 410
user541686 Avatar asked Nov 04 '22 14:11

user541686


1 Answers

Arguably, it's a mistake. However, it's possible that we're only given the public definition of the structure. Internally (when used by the Windows kernel), it might be defined as:

typedef struct _DISK_DETECTION_INFO {
  DWORD          SizeOfDetectInfo;
  DETECTION_TYPE DetectionType;
  union {
    struct {
      DISK_INT13_INFO    Int13;
      DISK_EX_INT13_INFO ExInt13;
    };
    DISK_INTERNAL_INFO   Private; // Used internally, when DetectionType = -1
  };
} DISK_DETECTION_INFO, *PDISK_DETECTION_INFO;

I wouldn't volunteer this as maintainable, safe, or portable, but it's possible.

DISK_INTERNAL_INFO could even exceed the size of the anonymous struct - provided that a user is never instantiating the object themselves the technique might even be considered useful for hiding extra data away from the user but keeping it with the structure. They'd never "see" past the anonymous struct.

like image 60
ta.speot.is Avatar answered Nov 15 '22 06:11

ta.speot.is