1

I am looking for the most elegant implementation of string literals with their size in a table in C. The main point is that I want the compiler to calculate sizeof("Some String Literal") during compile-time.

So far I can think of the following two possibilities (see code below):

  1. Type the string twice as done for Option A. This is not a good solution because of possible typing errors if there are many strings and a string must be changed.

  2. Define the string literals and then use these in the table as done with Option B

Or are there any more elegant solutions?

#define STR_OPTION_B "Option B"

typedef struct
{
    enum {
        OPTION_A,
        OPTION_B
    } optionIDs;
    char* pString;
    int sizeOfString;
}
tTableElement;

tTableElement table[] =
{
    { OPTION_A, "Option A", sizeof("Option A") },
    { OPTION_B, STR_OPTION_B, sizeof(STR_OPTION_B) }
};
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Anguel
  • 427
  • 1
  • 5
  • 12

1 Answers1

5

Use a #define macro that will put both the string, and the size of the string into your structure.

#define STR_ENTRY(x) x, sizeof(x)
tTableElement table[] =
{
    { OPTION_A, STR_ENTRY("Option A") },
    { OPTION_B, STR_ENTRY("Option B") }
};
#undef STR_ENTRY

This should expand to literally:

tTableElement table[] =
{
    { OPTION_A, "Option A", sizeof("Option A") },
    { OPTION_B, "Option B", sizeof("Option B") }
};
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
abelenky
  • 63,815
  • 23
  • 109
  • 159
  • Even though the lifetime of the macro is limited due to the `#undef`, you probably should avoid names that start with a leading underscore (especially when followed by an uppercase letter), though. – jamesdlin Mar 27 '13 at 19:54
  • 3
    @abelenky: All identifiers that start with a leading underscore and followed by an uppercase letter or another underscore are reserved in any scope. Identifiers with a leading underscore are reserved at global scope. (See http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier ) – jamesdlin Mar 27 '13 at 20:00