I recently started learning C using the K&R book (2nd ed.) and I'm just having trouble wrapping my mind around this solution to exercise 1-9 which is:
Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.
I found the following solution online and it mostly makes sense except for that semi-colon above putchar(' ');. Without it the program doesn't perform its function properly, what function does that semi-colon serve?
#include <stdio.h>
int main(void)
{
int c;
while ((c = getchar()) != EOF) {
if(c == ' ') {
while((c = getchar()) == ' ')
;
putchar(' ');
}
putchar(c);
}
}
Thanks in advance.
The statement:
while((c = getchar()) == ' ')
;
is indented incorrectly. It should read:
while((c = getchar()) == ' ')
;
The ;
is an empty statement equivalent to an empty block { }
.
This lonely ;
is somewhat confusing, so it is considered good style to add a comment or some other emphasis to clarify its true nature:
while ((c = getchar()) == ' ') {
/* nothing */
}
while ((c = getchar()) == ' ')
/* nothing */;
Some bold programmers write this even more confusing form (avoid it):
while((c = getchar()) == ' ');
I personally prefer this equivalent form:
while ((c = getchar()) == ' ')
continue;
The statement
while((c = getchar()) == ' ')
;
is parsed as
while((c = getchar()) == ' ');
which has the same effect as
while((c = getchar()) == ' ') {
/* Do nothing */
}
In other words, it's a while loop whose body has no effect. The act of checking the condition of the while loop reads characters and discards spaces, which is what you want to do.
If you delete the semicolon, then the while loop body ends up being the statement after the loop, which causes the wrong statement to repeat.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With