Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching If and Else Doesn't Produce Same Results

Tags:

c

if-statement

I've been working through some examples in The C Programming Language by K&R, but I'm kind of confused on a test that I did on exercise 1-12 where I switched the if and else statements.

The question goes as: Write a program that prints its input one word per line.

So basically to test out the \n while ignoring multiple spaces in between words, I first wrote this.

#include <stdio.h>

int main()
{
    int c;

    while ((c = getchar()) != EOF) {
        if (c == ' ' || c == '\t') {
            printf("\n");

        }
        else {
            putchar(c);
        }

    }
}

In this one, it would print out a new paragraph upon seeing blank spaces or tabs, and if it doesn't, then it copies exactly the input.

This code produced the results that I wanted (well there's still extra paragraphs from extra spaces in between words on input, but I'm ignoring that for now)

Then I decided to see what happened if I switched my if and else statements while changing the conditions, but it turns out that the result is not the same.

#include <stdio.h>

int main()
{
    int c;

    while ((c = getchar()) != EOF) {
        if (c != ' ' || c != '\t') {
            putchar(c);
        }
        else {
            printf("\n");
        }

    }

}

In this one, I wanted it to print out whatever wasn't a blank space or tab, and if it doesn't, it would create a new paragraph.

I expected that the new conditions would produce the same results. Instead it just copied what I put inputted. Does anyone know why this doesn't work?

like image 203
user1604449 Avatar asked Nov 22 '25 16:11

user1604449


1 Answers

    if (c != ' ' || c != '\t') {

This condition checks to see whether either c is not a space, or c is not a tab. This is always true, since c can't be both a space and a tab at the same time. Try:

    if (c != ' ' && c != '\t') {

You can read about this principle in more detail at De Morgan's Laws.

An alternative approach would let the compiler do the logical negation for you:

    if (!(c == ' ' || c == '\t')) {

however, some people (me included) would consider that harder to read because of the extra parentheses and the tiny ! on the left.

like image 192
Greg Hewgill Avatar answered Nov 25 '25 09:11

Greg Hewgill