vendredi 27 mars 2020

Why this if block with single statement must require a bracket to work properly?

//Here is the sample code to print it's input one word per line: //without bracket it doesn't work properly

#include <stdio.h>
#define IN 1
#define OUT 0

main() {
  int c, state;

  while ((c = getchar()) != EOF) {
    if (c == ' ' || c == '\t' || c == '\n')
      if (state == IN) {
        putchar('\n');
        state = OUT;
      } else {
        putchar(c);
        state = IN;
      }
  }
}

//when you put brackets around the nested if block(logically a single statement) inside the first if block it works properly

#include <stdio.h>
#define IN 1
#define OUT 0

main() {
  int c, state;

  while ((c = getchar()) != EOF) {
    if (c == ' ' || c == '\t' || c == '\n') {
      if (state == IN) {
        putchar('\n');
        state = OUT;
      }
    } else {
      putchar(c);
      state = IN;
    }
  }
}

Aucun commentaire:

Enregistrer un commentaire