Chris Croughton wrote:
On Mon, 16 May 2005 14:55:53 GMT, August Karlstrom
Chris Dollin wrote:
`*ptr++` is the standard C idiom for fetch-and-advance-pointer.
Incrementing in a separate statement is likely to make the code more
confusing, I'd have thought.
Confusing for the programmer who only has experience with C/C++,
maybe. In almost any other language (procedural at the statement
level) the incrementation is a separate statement.
If one is writing in C one should use C idiom, not Fortran idiom or Ada
idiom. The C idiom is x = *ptr++, it doesn't matter that in COBOL I'd
write something like MOVE X FROM ARRAY INDEXED BY I. ADD 1 TO I. Or
that in assembler I'd write:
mov bx, i[bp]
mov x, [bx]
inc i[bp]
Sure there are idioms in C, but the language is not exactly known for
putting the programmer into a straitjacket. It allows you to do
pretty much what you want. With the preprocessor you can even define
a new language ;-)
You can indeed (see a thread recently (somewhen in the last several
months, anyway) about someone doing just that), but anyone who finds
*ptr++ confusing is no more a "C programmer" than I am a "French
novelist". If you don't know the idioms then you don't know the
language. You /can/ write ptr = ptr + 1; instead of ++ptr if you want
(in some early compilers the forms ++i, i =+ 1 and i = i + 1 actually
generated different code deliberately), but any C programmer should be
equally at ease with any of them
Having the increment separate often loses some of the readability of the
language. Compare:
*ptr++ = a;
*ptr++ = b;
*ptr-- = c;
*ptr++ = d;
with:
*ptr = a;
++ptr;
*ptr = b;
++ptr;
*ptr = c;
--ptr;
*ptr = d;
++ptr;
The former is obvious (to any C programmer), the latter is visually
confusing and harder to maintain. Note "visually confusing", it's not
confusing to a C or C++ programmer as a concept, it is confusing to the
eye. There's a mistake in them which is visually obvious in the first
but not in the second. Merging lines:
*ptr = a; ++ptr;
*ptr = b; ++ptr;
*ptr = c; --ptr;
*ptr = d; ++ptr;
makes that mistake more obvious again, but makes maintenance messier
when 'b' becomes 'fred' and you need to line up the others.