I would like to print a line break in C to help separate print statements for debugging. Here are two versions that I have now:
int main(void)
{
repeat('-', 21);
REPEAT('-', 21);
}
Function:
void repeat(const char value, const unsigned int count) {
char vals[count+1];
vals[count] = '\0';
for (unsigned int i=0; i < count; i++)
vals[i] = value;
printf("%s\n", vals);
}
Macro:
#define REPEAT(value, count) \
char vals[count+1]; \
vals[count] = '\0'; \
for (unsigned int i=0; i < count; i++) \
vals[i] = value; \
printf("%s\n", vals);
I am quite new to C and this is actually the first function-macro I've used, so my questions is which of the above approaches is more preferred? Why would one approach be better than the other? The 'function' approach seems a bit cleaner to me, but I see so many macros in other's code that it seems like any utility that can be made into a macro is often done so.
putcharrepeatedly; do not create a string for it. Except, if the same sequence is going to be printed repeatedly, it might make sense to create a static array for it.putcharinstead of a local array to print, etc?int n = 3; REPEAT('x', n++);.