Using a macro is OK in C89 which did not have inline functions. But your macro has extremely bad style and I believe it would be considered unacceptable in most, if not all, places:
- It messes with a static variable
i
- It doesn't have
()
, yet it executes statements
- It doesn't play nicely with surrounding code
- It evaluates
s
more than once
For example
int i = 3;
if ( test )
printS;
else // oops, compilation error - invalid "else"
something_else();
printf("%d\n", i); // oops, not 3
To write this macro properly (leaving out for now the fact that the actual code could be improved - I want to demonstrate how to use a variable evaluated more than once):
#define PRINTS(s) do { int i; for (i = 0; (s)[i]; ++i) printf("%c", (s)[i]); } while (0)
Now you can safely use it exactly like you would use a function:
int i = 3;
char const *s = "lol";
if ( condition )
PRINTS("kek"); // prints "kek", not "lol"
else
other_stuff();
printf("%d\n", i); // 3
The purpose of using ALL CAPS is to warn the reader that it is a macro and not a function, so it might evaluate the argument twice. Personally I use ALL CAPS if it does evaluate the argument twice, and a normal function name if it doesn't, although different places have different standards.
Now: it would be much better to make the macro only evaluate its argument once. That makes it a lot more flexible. Of course the simplest way to do this is to call puts(s);
or printf("%s, (s));
. Another way (let's say the situation was more general than this) would be to factor out the check of (s)[i]
:
#define printS(s) do { char const *p; for (p = (s); *p; ++p) printf("%c", *p); } while (0)
main
, though, there are no real problems. \$\endgroup\$