Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Designated initializers

Use case

Initialize structs by field name for clarity.

Explanation

Name fields explicitly. Order must match declaration. Unspecified fields are zero-initialized.

Code

#include <cstdint>
#include <iostream>

// https://en.wikipedia.org/wiki/Mach-O
struct MachHeader64 {
  uint32_t magic;
  // uint32_t cputype;
  // uint32_t cpusubtype;
  uint32_t filetype;
  uint32_t numofcmds;
  // uint32_t sizeofcmds;
  // uint32_t flags;
  // uint32_t reserved;
};

int main() {
  MachHeader64 hdr{
      .magic = 0xFEEDFACF,
      .filetype = 0x2, // MH_EXECUTE
      .numofcmds = 0x0,
  };

  std::cout << "Magic: 0x" << std::hex << hdr.magic << "\n";
  std::cout << "Num of cmds: " << std::dec << hdr.numofcmds << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/designated-initializers
Magic: 0xfeedfacf
Num of cmds: 0