[KLUG Programming] substr in C?

Robert G. Brown programming@kalamazoolinux.org
Mon, 21 Jul 2003 17:42:24 -0400


On 21 Jul 2003 14:59:57 -0400, Adam Williams <adam@morrison-ind.com> wrote:

>I remember by C instructor telling me that pointer arithmetic was bad
>(like oldstring+5).  But you imply that it is OK?  Was my C instructor
>on crack, or why did he make that statement?

The only drug that seems to apply here is known as "form follows function".

The tendency among instructors that are running intro C programming classes
has been to teach it as more of a high level language. This means that in
place of oldstring+5, they will present it as oldstring[5] if they can. I
like the notion that, just as pointer arithmetic commutes, so does bracket
indexing, so 5[oldstring] is fine too.

There is value in knowing all these constructs and what they imply, since 
the notion is that they allow a program to be more readable. If what you're
doing is indexing a character string, it might help future readers of the
code to read something of the form array[index], while more complex refer-
ences into memory may be noted in the form array+index. This is not a ques-
tion of "correctness"; C is not intended as a notation. It is more a matter
of coding style, where some folks are trying to make some semantic implica-
tions, based on how the code is written.

							Regards,
							---> RGB <---