And the code without braces is still entirely valid standard C, the warning is essentially just a lint to protect against typos (similar to JS linters warning about '===' vs '==').
The flaw was minor in this case because the identifier names and lack of body make the intention clear, but my point is that there are a lot of minor things in C that can come and bite you at any time.
Edit: You are right, I don't see a way this could have been implemented more readable without sacrificing some performance.
First thing I thought of was:
void cp(const char* from, char* to) {
while (*from) {
*to = *from;
to++;
from++;
}
}
But that does not reduce to the original case.As for performance: I don't think such details matter much, first, compilers are pretty good to turn "readable but inefficient" code into the same optimal output (aka "zero cost abstraction").
And a really performance-oriented strcpy() wouldn't simply copy byte by byte anyway, but try to move data in bigger chunks (like 64-bit or even SIMD registers). Whether this is then actually faster also depends on the CPU though.
char c;
do
{
c = *src++;
*dst++ = c;
}
while (c != 0);
The post-increment is idiomatic enough in C-based languages that I wouldn’t worry about that.It is a shame post-test loops aren’t more popular, given the similarity to the assembly they output. Seems more mechanically sympathetic. Oh well, at least it is an excuse to whip out the goto.
repeat
...
until c = 0;
which might be even clearer for this use case.The order things happen in *this++ is not obvious unless you know a bunch of C-specific rules, while the ordering of multiple statements is obvious even to someone who doesn't know C. Perhaps C programmers should find this obvious, but it seems to me more like cognitive overhead which has a non zero chance of confusing someone at some point.
E.g. I guess for a mathematician, all imperative languages are probably 'weird', while something like Haskell feels more familiar?
This isn't a "clever one-liner" it is a clear and precise syntax for expressing the operation the machine actually performs.
while(copy(current(stream_a), current(stream_b)) and not end_of_stream(stream_a))
You might prefer the above, but then, that's every other major language. The beauty of C is that the above code has to compile to something like the C version. C just allows you to actually express it
No it’s not. Your compiler will almost certainly translate this into vector instructions, at least.
You shouldn't just blindly let your tooling dictate how you work. It's a tool that's supposed to work for you, not control you. -Wall and -Wextra are good baselines but I always disable some of their warnings because I don't need the hassle on known good code.
The code as written was described as beautiful, yet would not have passed -Wall.
It's those little things that can easily get you in C, and there are so many little things to consider.