If and how much space any attempt at optimization saves depends on the compiler. There is usually an option for a "minimum size build". Compiling the program and checking the results is the only method to see if space was truly saved. There is a good chance that any compiler, aiming for a minimum size build, that sees const char strUser[] = "[USER] ";
will create exactly one string in the program, and point to that string wherever it is used.
Here are three options you could try. One using a macro, one using a function, and one using a different function call. I know you asked for "during compilation with no extra functions", but this function may very well be "optimized away" during compilation.
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
// warning: ISO C does not permit named variadic macros
#define IPRINTF1(format, args...) printf("[USER] " format, ##args);
// An iprintf wrapper that first prints the desired string.
void iprintf2(const char *restrict format, ...)
{
printf("[USER] ");
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
}
int main(void)
{
const int userID = 5;
const char strUser[] = "[USER] ";
IPRINTF1("created user:%d\n", userID);
iprintf2("created user:%d\n", userID);
// Passing the string as an additional parameter.
// This may be the best solution code quality-wise, as it avoids repetition while keeping the code dynamic.
printf("%screated user:%d\n", strUser, userID);
}
Actually concatenating two strings with +
as in Python is not possible in C. Instead there is the strcat function. However, this involves allocating a buffer that is large enough, making a copy of the format
string, always guaranteeing that the restrict
qualifier holds... This is almost certainly not worth it.
Also, this is all under the assumption that saving a couple of bytes is worth the decrease in code quality.