0

I have a constant private data structure which has a public accessor. I've seen two styles for doing this:

Style A: Define private data structure at top level of file

static const char *days[] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};

const char *day_name(uint8_t day) {
  if (day >= sizeof(days) / sizeof(const char *)) {
    return "Unk";
  } else {
    return days[day];
  }
}

Style B: Define private data structure within accessing function

const char *day_name(uint8_t day) {
  static const char *days[] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};

  if (day >= sizeof(days) / sizeof(const char *)) {
    return "Unk";
  } else {
    return days[day];
  }
}

These both compile to the same code. (Crucially, in the second case, the data structure is NOT allocated on the stack.) Is there a stylistic preference for chosing one over the other?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.