I have a question. In my own webserver I have the following code at the file scope:
typedef struct {
char *slice;
int length;
} values_index;
const char *aHeaderKeys[] = {
/* You can add here whatever you want! */
"Accept",
"Accept-Charset",
"Accept-Encoding",
"Accept-Language",
"Authorization",
"Expect",
"From",
"Host",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Range",
"If-Unmodified-Since",
"Max-Forwards",
"Proxy-Authorization",
"Range",
"Referer",
"TE",
"User-Agent",
"Connection"
};
int nHeadersSizes[sizeof(aHeaderKeys) / sizeof(*aHeaderKeys)];
values_index aHeaderValuesIndexes[sizeof(aHeaderKeys) / sizeof(*aHeaderKeys)];
const int nHeadersLen = sizeof(aHeaderKeys) / sizeof(*aHeaderKeys);
But, since aHeaderKeys
is an array of a constant length of constant strings, it's stupid to calculate the length of the array during the execution of the program and it should be better to write it manually:
typedef struct {
char *slice;
int length;
} values_index;
const char *aHeaderKeys[20] = {
/* You can add here whatever you want! */
"Accept",
"Accept-Charset",
"Accept-Encoding",
"Accept-Language",
"Authorization",
"Expect",
"From",
"Host",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Range",
"If-Unmodified-Since",
"Max-Forwards",
"Proxy-Authorization",
"Range",
"Referer",
"TE",
"User-Agent",
"Connection"
};
int nHeadersSizes[20];
values_index aHeaderValuesIndexes[20];
const int nHeadersLen = 20;
But the number of the elements of my array can change during the developing process, so every time I want to add another element I have to change manually the length everywhere. Now my question is: is it possible to write a preprocessor macro like the following one I wrote in JavaScript (as pseudocode)?
var aHeaders = [
"Accept",
"Accept-Charset",
"Accept-Encoding",
"Accept-Language",
"Authorization",
"Expect",
"From",
"Host",
"If-Match",
"If-Modified-Since",
"If-None-Match",
"If-Range",
"If-Unmodified-Since",
"Max-Forwards",
"Proxy-Authorization",
"Range",
"Referer",
"TE",
"User-Agent",
"Connection"
];
var sExplodedText = "const char *aHeaderKeys[" + aHeaders.length + "] = {\n\t\/* You can add here whatever you want! *\/\n\t\"" + aHeaders.join("\",\n\t\"") + "\"\n};\n\nint nHeadersSizes[" + aHeaders.length + "];\nvalues_index aHeaderValuesIndexes[" + aHeaders.length + "];\nconst int nHeadersLen = " + aHeaders.length + ";";
alert(sExplodedText);