LOGBOOK

HELP

← again tap: answer good → ↑ swipe up at the end: next

1 / 8
Other keys: show • Space: good • 1-4: rate • 0: skip • 5: flag

Question

How does the if-else statement work in C, and what's the dangling else problem?

Answer

The condition goes in parentheses and each branch takes one statement (use braces for more); the "dangling else" trap is that else binds to the nearest unmatched if.

// Single statement, no braces needed
if (a > b) c = a-b;
if (b > a) c = b-a;
// else is optional
else c = a-b;

// Braces for multiple statements
if (2*a == b) {
    b = b*2;
    a = a+1;
} else {
    c = 3;
    d = 4;
}

The dangling else problem:

if (a > b)
    if (b > a) c = b-a;
// Which 'if' does this 'else' belong to?
else c = a-b;

Rule: else matches the closest unmatched if.

So the above is actually:

if (a > b) {
    if (b > a) c = b-a;
    // Belongs to inner if!
    else c = a-b;
}

Best practice: Always use braces to avoid ambiguity:

if (a > b) {
    if (b > a) {
        c = b-a;
    }
} else {
    c = a-b;
}

Go deeper:

or press any other key

Question

How does C evaluate conditions (true/false)?

Answer

Any non-zero value counts as true and zero counts as false — C89 has no built-in boolean type at all.

// These are equivalent:
// True if a != 0
if (a)
// Explicit comparison
if (a != 0)

// True if b == 0
if (!b)
// Explicit comparison
if (b == 0)

No native true/false in C89:

// Common pattern:
#define true  1
#define false 0

// Or use stdbool.h (C99):
#include <stdbool.h>
bool flag = true;

Warning with #define true/false:

#define true 1
int a = 5;
// FALSE! 5 != 1, even though 5 is "truthy"
if (a == true)
// TRUE! Any non-zero is truthy
if (a)

Tip: Never compare against true. Just use if (a) or if (!a).

or press any other key