简体   繁体   中英

Compile-time array concatenation

C supports concatenating constant strings at compile-time. Can I do the same for any constant array? (Eg 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".

No

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM