In my previous post I talked about C++’s “relatively nerfed” form of designated initializers. This time I want to show you a neat thing you can do with C’s full-power designated initializers. I first saw this pattern in Ben Klemens’ book 21st Century C (2014), pages 226–228. (Godbolt.)

struct IdealVolumeArgs {
  double atm;      // P
  double moles;    // n
  double kelvin;   // T
};
#define ideal_volume(...) ideal_volume_impl( \
  (struct IdealVolumeArgs){ \
    .atm=1, .moles=1, .kelvin=273.15, __VA_ARGS__ \
  })
double ideal_volume_impl(struct IdealVolumeArgs args) {
  // The ideal gas law: PV = nRT
  return args.moles * 0.082057366 * args.kelvin / args.atm;
}

int main() {
  printf("1 mole of gas at STP occupies %g L\n",
    ideal_volume());
  printf("1 mole of gas at 100°C occupies %g L\n",
    ideal_volume(.kelvin = 373.15));
  printf("2 moles of gas at 100°C occupies %g L\n",
    ideal_volume(.kelvin = 373.15, .moles = 2));
  printf("2 moles of gas at 0°C and 2 atm occupies %g L\n",
    ideal_volume(.moles = 2, .atm = 2));
}