Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <string.h>
- #include <stdio.h>
- /** concatenate strings without limit */
- #define max_concat 256
- /* concatenate */
- #define CONCAT(...) ( __extension__ ({ \
- char* sarray[] = { __VA_ARGS__ , NULL }; \
- char* out = calloc(max_concat, sizeof(char)); \
- do { size_t n = 0; \
- while (sarray[n] != NULL) \
- { sprintf( out, "%s%s", out, sarray[n] ); n++; } \
- }while(0); \
- out = realloc(out, strlen(out)+1); \
- }))
- int main( int argc, char** argv, char** env)
- {
- char* str = CONCAT( "dog", "cat", "horse", "butt", "smacker", " - ", "SNAP", "!" );
- fprintf(stdout, "%s\n" , str);
- free (str);
- return 0;
- }
- /** NOTES
- * the ( __extension__({ and subsequent }))
- * enclose the macro as a gnu extension so that
- * it is not flagged as a warning in pedantic mode.
- * It also creates a scope where statically allocated
- * variables can be created and disposed of at the "return".
- *
- * The last statement is what the macro "returns", in this case
- * the dynamically allocated string (out). The realloc command
- * is not really needed but right-sizes the string. It still must
- * be freed later.
- */
Add Comment
Please, Sign In to add comment