开发者

Compile-time array concatenation

C supports concatenating constant strings at compile-t开发者_如何学Cime. Can I do the same for any constant array? (E.g. concatenate two char ** arrays.)


Basically no, but you can always workaround this with the preprocessor. The trick is to define arrays without curly braces:

#define ARRAY_ONE "test1", "test2", "test3"
#define ARRAY_TWO "testa", "testb", "testc"

Now, you can join arrays in compile time with comma. To use them, however, you will either have to sorround them with curly braces or use a macro:

#define ARR(...) {__VA_ARGS__}

You can now use a single array or any concatenation you need like so:

char *arr1[] = ARR(ARRAY_ONE);
char *arr2[] = ARR(ARRAY_TWO);
char *arrc1[] = ARR(ARRAY_ONE, ARRAY_TWO);
char *arrc2[] = ARR(ARRAY_ONE, ARRAY_TWO, ARRAY_ONE, ARRAY_ONE);

Using macros to achieve such results is bad practice, though.


Short answer: No.

Longer short answer: String literals are indeed character arrays, but not all character arrays are string literals. The compile-time concatenation works only for string literals. No arrays have that "feature".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜