Course contentsShow
← C
Lesson 1202 of 1,21916. Practice and ProjectsFree lesson

Indentation and whitespace rules

Indentation and whitespace rules

What you'll learn: How to use spacing and tabs to transform a dense block of text into a readable, professional roadmap for your logic.

The "Messy Closet" Problem

Imagine opening a closet where every shirt, shoe, and coat is jammed into one giant pile. You could eventually find your sneakers, but it would take ten minutes of digging. Code is exactly the same. The C compiler doesn't care if your code is a single, mile-long line or a beautiful masterpiece; it only sees the semicolons. However, humans—including your future self—need visual cues to understand where a thought begins and ends.

Indentation: Showing Hierarchy

The most important rule in C style is that every time you open a curly brace {, the next line should be indented. This creates a "nesting" effect. When you see a block of code shifted to the right, your brain instantly recognizes: "This code belongs to the function or loop above it."

Most professionals use either four spaces or one tab per level. The key is consistency. If you mix them, your code will look like a zigzagging staircase on someone else’s screen.

Whitespace: Letting Code Breathe

Whitespace is the "breathing room" between your operators and variables. Look at these two examples: int x=5+(y*10); (Cramped) int x = 5 + (y * 10); (Breathable)

By adding spaces around operators like =, +, and *, you make the math stand out. Similarly, always put a blank line between different "chapters" of your code, such as between variable declarations and the actual logic, or between two different functions.

Professional Example

Notice how the indentation clearly shows which code is "inside" the main function and which is "inside" the if statement:

#include <stdio.h>

int main() {
    int temperature = 25;
    int is_sunny = 1;

    // Use a blank line to separate setup from logic
    if (temperature > 20) {
        // This is indented because it belongs to the 'if'
        printf("It is a warm day.\n");
        
        if (is_sunny) {
            // Doubly indented: belongs to 'if' inside an 'if'
            printf("Don't forget your sunglasses!\n");
        }
    }

    return 0;
}

Key takeaway

Consistent indentation and spacing turn "code that works" into "code that communicates."