Home > database >  Confusion with comparison operators
Confusion with comparison operators

Time:11-19

This solution is for the 1-12 exercise from the C programming language book. The question is to write a program that prints its input one word per line.

I found the following solution:

#include <stdio.h>
int main(void)
{
  int c;
  int inspace;

  inspace = 0;
  while((c = getchar()) != EOF)
  {
    if(c == ' ' || c == '\t' || c == '\n')
    {
      if(inspace == 0)
      {
        inspace = 1;
        putchar('\n');
      }
      /* else, don't print anything */
    }
    else
    {
      inspace = 0;
      putchar(c);
    }
  }
  return 0;
}

Can someone please explain why is inspace == 0 used in the if argument and how the logic works later with inspace = 1 in the statements?

Does the 0 indicate space in the input?

CodePudding user response:

Older versions of C didn't have a boolean data type for "true" and "false".

Instead, they just used integers and decided that 0 means "false" and anything else means "true".

With this in mind part of the above code could be read like:

if(c == ' ' || c == '\t' || c == '\n')
    {
      if(inspace == FALSE)
      {
        inspace = TRUE;
        putchar('\n');
      }
      /* else, don't print anything */
    }
    else
    {
      inspace = FALSE;
      putchar(c);
    }

Essentially, the logic is like:

  • If the next character is the first white space character after something that wasn't white space (inspace == FALSE) print a newline character

  • Otherwise if the next character is just more white space in the existing white space (inspace == TRUE) just ignore it

  • Otherwise print it

CodePudding user response:

Algorithm flaws

Although there may be some confusion with comparisons, there exist algorithm flaws. Let us handle that first.

Should use inspace = 1; before the loop.

Add if (!inspace) putchar('\n'); after the loop.


Concerning comparisons when using a 2-state variable like inspace

  • Use <stdbool.h>. It have been available since 1999.
  • Code inspace as a bool and not an int.
  • Drop the ==, !=.

Do not code like abd == true or def == false. Do not create TRUE or FALSE.

#include <stdbool.h>
#include <stdio.h>

int main(void) {
  int c;
  bool inspace = true;  // Note this is the opposite state of OP's code.

  while((c = getchar()) != EOF) {
    if(c == ' ' || c == '\t' || c == '\n') {
      if(!inspace) {
        inspace = true;
        putchar('\n');
      }
      /* else, don't print anything */
    }
    else {
      inspace = false;
      putchar(c);
    }
  }

  if (!inspace) {
    putchar('\n');
  }
  return 0;
}

Other improvements

Use <ctype.h>

// if(c == ' ' || c == '\t' || c == '\n')
if (isspace(c))  // For all white-spaces, not just 3 of them.
  • Related