Is the following code valid/good practice in C?
int x = 1;
printf(x == 1 ? "%d second elapsed" : "%d seconds elapsed", x);
It compiles fine, so I assume it is fine (also since it is just syntactical sugar for an if-else block), but if anyone has some additional insight, I would appreciate it, thank you.
P.S., I assume the same goes for C++?
Yes!
Opinionated: After wading though tons of code written by programmers writing kernels, drivers and misc. utility programs that are usually considered "good", I think the consensus is that "it's fine". Not only is it safe - it can also be made easily readable.
A small, non-opinionated, note: Compilers are allowed to make string literals overlap. If you have two string literals, "Hello world"
and "world"
and compile your program will full optimization, you may find that the pointer to 'w'
in "world"
is actually within the "Hello world"
string literal, since they are both valid, null-terminated strings. Example:
ptr1
|
V
hello world\0
^
|
ptr2
However, that optimization cannot be applied to strings like yours, since the different part is in the middle of the string literal.
I therefore suggest:
printf("%d second%s elapsed", x, x == 1 ? "" : "s");
Another opinion of mine is that doing it like this also makes it easier to read.