Originally Posted by
jeffcobb
Yep this is exactly why any variable that is not a counter should say what it is...pc should be something like previousCharacter, c could be currentCharacter, stuff like that, it makes the meaning of the code so much more obvious as anyone who has to maintain anothers code will tell you...
Self-documenting code. Any easier?
Code:
#include <stdio.h>
const int Success = 0;
const char Space = ' ';
/* count lines in input */
int main(int argc, char*argv[])
{
int nReturnCode = Success;
int currentCharacter, previousCharacter;
/* set previousCharacter to a value that wouldn't match any character, in case
this program is ever modified to get rid of multiples of other
characters */
previousCharacter = EOF;
while ((currentCharacter = getchar()) != EOF)
{
if (currentCharacter == Space)
{
if (previousCharacter != Space) /* or if (previousCharacter != c) */
{
putchar(currentCharacter);
/* We haven't met 'else' yet, so we have to be a little clumsy */
if (currentCharacter != Space)
{
putchar(currentCharacter);
}
previousCharacter = currentCharacter;
}
}
}
return Success;
}
I have to disagree. Self-documenting code would be 'prevChar' or even 'prevCh', not 'previousCharacter', which may as well be 'theQuickBrownFoxJumpedOverTheLazyDog'. You also used horrible indentation, probably due ot a mix of tabs and spaces, and more importantly, you complete broke the code. It doesn't do anything remotely close to what it supposed to any more.
Code:
const char space = ' ';
does not get you anything whatsoever.
Unused code such as
Code:
int nReturnCode = Success;
is just silly also. Dead code is a burden. The more lines of code you have, the more bugs you most likely have.
You have some good intentions with making it self-documenting, but your execution of that idea came out absolutely terrible. The originally posted code was far better.
With regards to commenting, what experience teaches you is that it is more important for comments to say WHY the code does what it does, rather than WHAT it does.
Here's how I would recommend writing this:
Code:
#include <stdio.h>
int main() {
/* set prevch to a value that wouldn't match any character, in case
this program is ever modified to get rid of multiples of other
characters */
int ch, prevCh = EOF;
while ((ch = getchar()) != EOF) {
/* Output the char as long a both this char
and the last one were not both spaces */
if (ch != ' ' || prevCh != ' ')
putchar(ch);
prevCh = ch;
}
return 0;
}