Anguel
Anguel

Reputation: 427

Implementing string literals with their size in a table

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) }
};

Upvotes: 1

Views: 157

Answers (1)

abelenky
abelenky

Reputation: 64740

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") }
};

Upvotes: 5

Related Questions