* Which one is better, and why? printf("X");
or printf("%s", "X");
Neither is better in that case unless the string "X" is not placed in a read-only section of memory, in which case you'd be guarding against memory modification that can potentially expose private data. That said, it would be a bit paranoid to write
printf("%s%s%s", "Hello, ", name, "!\n");
instead of
printf("Hello, %s!\n", name);
. However,
printf(user_input);
is definitely worse than
printf("%s", user_input);
. The reason why one is better than the other is left as an exercise to the reader.
I'd also add:
* Why are
*++ptr
and
*ptr++
potential sources of bugs, and what makes
++*ptr
safe compared to the other two expressions?
Apart from secure coding is the matter of code style. It's important to remember that "comprehensible" and "readable" are not always the same thing.
while (*dst++ = *src++);
is a lot more readable, but it's more difficult to comprehend when compared to a slightly longer
for
loop equivalent, and you may not remember what such "clever" code does if/when you come back to it later.
There are all sorts of styles like
style(9) in FreeBSD, Linux, Google, and GNU. You can search for
coding style on your favorite search engine to find many of the popular ones. Also, a wide variety of opinions exist regarding all sorts of topics, which may not even be specific to C/C++; one example is limiting line length to 72 screen columns, which is absurd
if using(long_variable_names) and qualified.names() in languages_like("Python"):
Tools exist to automatically format your C code.
indent(1), or the GNU equivalent
gindent(1) (
devel/gindent), are the classic go-to solution. More modern options that may work better include
clang-format (available with ports like
devel/llvm10 if you don't already have the program installed) and
Artistic Style (
devel/astyle). Use whatever works for you or manually format your code however you want (e.g. you might follow
style(9), even if you're not doing FreeBSD-related coding).