How to clear console in C?

In C, clearing the console or output screen can be achieved using several methods. While clrscr() from conio.h was commonly used in older compilers, modern standard C uses system() calls for cross-platform compatibility.

Note: The examples below use system() calls which work in most environments. For online compilers, console clearing may not be visible as output is captured after program execution.

Syntax

The following are standard methods to clear the console in C −

#include <stdlib.h>
system("cls");    /* Windows */

Or,

#include <stdlib.h>
system("clear");  /* Linux/macOS */

Example 1: Using system("cls") for Windows

This method works on Windows systems −

#include <stdio.h>
#include <stdlib.h>

int main() {
    printf("This text will be cleared...\n");
    printf("Press Enter to clear screen\n");
    getchar();
    
    system("cls");  /* Clear screen on Windows */
    
    printf("Screen cleared! New content appears here.\n");
    return 0;
}
Screen cleared! New content appears here.

Example 2: Using system("clear") for Linux/macOS

This method works on Unix-based systems −

#include <stdio.h>
#include <stdlib.h>

int main() {
    printf("Initial content on screen\n");
    printf("About to clear...\n");
    
    system("clear");  /* Clear screen on Linux/macOS */
    
    printf("Console cleared successfully!\n");
    printf("This is the new content.\n");
    return 0;
}
Console cleared successfully!
This is the new content.

Example 3: Cross-Platform Clear Function

A portable solution that works on both Windows and Unix systems −

#include <stdio.h>
#include <stdlib.h>

void clearScreen() {
    #ifdef _WIN32
        system("cls");
    #else
        system("clear");
    #endif
}

int main() {
    printf("Content before clearing...\n");
    printf("Line 1\n");
    printf("Line 2\n");
    
    clearScreen();
    
    printf("Screen cleared using cross-platform method!\n");
    return 0;
}
Screen cleared using cross-platform method!

Key Points

  • system("cls") works on Windows systems
  • system("clear") works on Linux, macOS, and Unix systems
  • Always include <stdlib.h> header for system() function
  • Avoid clrscr() from conio.h as it's non-standard and not portable

Conclusion

Use system("cls") for Windows and system("clear") for Unix-based systems to clear the console. For portable code, use preprocessor directives to choose the appropriate command based on the target platform.

Updated on: 2026-03-15T09:57:55+05:30

22K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements