Course contentsShow
← C
Lesson 271 of 1,2194. Control FlowFree lesson

Infinite loops: while(1) and while(true)

Infinite loops: while(1) and while(true)

What you'll learn: How to create a loop that runs forever and why you would want to do it.

The loop that never sleeps

In previous lessons, we used the while loop to repeat code until a certain condition became false. But what happens if the condition is always true? You get an infinite loop.

In C, any non-zero number is treated as "true." Because the number 1 is always non-zero, writing while(1) creates a loop that, theoretically, will never stop. It’s like a ceiling fan: once you flip the switch, it keeps spinning until an outside force (like pulling the plug) stops it.

How to write them

There are two common ways to write an infinite loop in C:

  1. The Classic Way: while(1) is the traditional C approach. It’s fast, simple, and recognized by every C programmer.
  2. The Modern Way: If you include the library <stdbool.h>, you can write while(true). This does the exact same thing but is often easier for humans to read.
#include <stdio.h>
#include <stdbool.h>

int main() {
    // This loop will print forever!
    while(1) {
        printf("The engine is running...\n");
        
        // In a real program, we would use a 'break' 
        // statement to eventually exit this loop.
    }

    return 0;
}

Why would you want this?

An infinite loop might sound like a mistake (and if you do it by accident, your program will "freeze" or "hang"). However, they are essential for specific tasks:

  • Operating Systems: Your computer's OS stays in an infinite loop waiting for you to click or type. If the loop ended, your computer would shut down.
  • Embedded Systems: A microwave or a digital watch runs an infinite loop to constantly check the time and sensor inputs.
  • Game Loops: Video games use a "main loop" to constantly redraw the screen and check for player movement.

Usually, inside an infinite loop, we include a specific condition (using an if statement and a break command) to stop the loop when a specific event occurs, like the user clicking "Exit."

Key takeaway

An infinite loop created with while(1) or while(true) runs its code block repeatedly until the program is manually stopped or an internal "break" command is triggered.