Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

K&R - Exercise 1-9 - Removing Spaces [duplicate]

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.

like image 208
shotgunbilly Avatar asked Jul 16 '17 15:07

shotgunbilly


2 Answers

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;
like image 158
chqrlie Avatar answered Sep 24 '22 09:09

chqrlie


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.

like image 30
templatetypedef Avatar answered Sep 25 '22 09:09

templatetypedef