bryanph
bryanph

Reputation: 1012

C K&R 1.5.4 Word Counting Exercise 1-9

I was wondering why the code below doesn’t work exactly like the code below it. What the code is supposed to do, is to remove multiple consecutive spaces and just display one space: so 'it works' becomes 'it works'. The first piece of code just keeps it like 'it works'.

Doesn't work

#include <stdio.h>

main(){
    int c;
    int lastspace;

    lastspace = 0;
    while((c = getchar()) != EOF){
        if(c != ' ')
            putchar(c);
            lastspace = 0;
        if(c == ' '){
            if(lastspace == 0){
            lastspace = 1;
            putchar(c);
            }
        }
    }
}

Works

#include <stdio.h>

main(){
    int c
    int lastspace;

    lastspace = 0;
    while((c = getchar()) != EOF){
        if(c != ' ')
            putchar(c);
        if(c == ' '){
            if(lastspace != c){
            lastspace = c;
            putchar(c);
            }
        }
    }
}

Upvotes: 1

Views: 173

Answers (1)

simonc
simonc

Reputation: 42165

In your first example

if(c != ' ')
    putchar(c);
    lastspace = 0;

doesn't place {} braces after the if statement so only the immediate following statement is executed conditionally. Changing indentation and adding braces shows that the code is actually

if(c != ' ') {
    putchar(c);
}
lastspace = 0;

This is the reason why some coding standards mandate the use of {} following all control statements.

Upvotes: 5

Related Questions