I went back and looked at my source for this chapter (the calculator program) and remembered having a similar struggle understanding the code.
To sort it out, I wrote three versions of loops that did the same thing. One of them looks nearly identical to Old Pedant's #2 version:
Code:
while( (str[i] = str[j++]) != '\0' )
{
if( str[i] != ' ' )
i++;
}
For some reason it took me an hour of fiddling to get my head around it. I'm glad I spent the time however, because I can see pointer notation more clearly when I look at it now, having constructed some alternatives to understand what the code was doing.
In defense of the author, he avoids always showing the most optimal method of constructing simple code segments in favor of showing different ways of accomplishing the same thing. While this can sometimes lead to frustration, the persistent student will benefit, as he'll gain practice with alternative ways of accomplishing the same task.
I agree with OP, and prefer array notation in most circumstances -- it's clearer and easier to read (and write); however the C/C++ programmer should be comfortable with at least basic pointer arithmetic techniques. These little exercises are designed to help give that familiarity.
I settled on a for loop version, because I liked being able to initialize the iterators together for compactness:
Code:
for( int i=0, j=0; (str[i] = str[j]) != '\0'; j++ )
if( str[i] != ' ' )
i++;
I agree that tight source can create obfuscation, and so clearer code is usually desired, but this is a small function that works fine as a black box: pass it a string, and it will eat the spaces.
Plus, I was trying to think a little outside-the-box in my for loop usage. This was the first time I'd used compound initialization in a for loop, and an evaluation expression that wasn't "i is less than something."
Thanks for the code samples, Old Pedant.
