Disclaimer: I know perfectly well the semantics of prefix and postfix increment. So please don't explain to me how they work.
Reading questions on stack overflow, I cannot help but notice that programmers get confused by the postfix increment operator over and over and over again. From this the following question arises: is there any use case where postfix increment provides a real benefit in terms of code quality?
Let me clarify my question with an example. Here is a super-terse implementation of strcpy
:
while (*dst++ = *src++);
But that's not exactly the most self-documenting code in my book (and it produces two annoying warnings on sane compilers). So what's wrong with the following alternative?
while (*dst = *src)
{
++src;
++dst;
}
We can then get rid of the confusing assignment in the condition and get completely warning-free code:
while (*src != '\0')
{
*dst = *src;
++src;
++dst;
}
*dst = '\0';
(Yes I know, src
and dst
will have different ending values in these alternative solutions, but since strcpy
immediately returns after the loop, it does not matter in this case.)
It seems the purpose of postfix increment is to make code as terse as possible. I simply fail to see how this is something we should strive for. If this was originally about performance, is it still relevant today?
strcpy
method this way (for reasons you have already mentioned).int c = 0; c++;