'Why must this 'if' block with a single statement 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;
}
}
}
Solution 1:[1]
In the first version you outer if body is this
if (state == IN) {
putchar('\n');
state = OUT;
} else {
putchar(c);
state = IN;
}
While in the second is this
if (state == IN) {
putchar('\n');
state = OUT;
}
So with the second one the else is associated with the outer if, with the first it is with the inner if.
Solution 2:[2]
In the first example, the else statement is binding the the second if statement.
if () if () {} else () {}
Which is equivalent to...
if () { if () {} else () {} }
In the second example, the else statement is binding to the first if statement.
if () { if () {} } else () {}
This occurs because the added brackets enclose the second if statement inside a block scope, where the else exists outside of that scope. Without the added brackets, the else lies within the same scope as the second if and is interpreted as a single chained statement.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eraklon |
| Solution 2 | SpaceKatt |
