kbhit in C language

The kbhit() function in C checks if a key has been pressed on the keyboard without waiting for the Enter key. It returns a non-zero value if a key is available to be read, otherwise returns zero. However, kbhit() is non-standard and platform-specific (Windows/DOS only).

Syntax

int kbhit(void);

Parameters

  • None: The function takes no parameters.

Return Value

  • Returns a non-zero value if a key has been pressed.
  • Returns zero if no key is pressed.

Example

Note: This example uses Windows-specific headers (conio.h) and will not compile in standard C environments. It's provided for educational purposes to show the concept.

#include <stdio.h>
#include <conio.h>

int main() {
    char ch;
    printf("Press keys (ESC to exit)<br>");
    
    while (1) {
        if (kbhit()) {  // Check if a key is pressed
            ch = getch();  // Get the character without pressing Enter
            
            if ((int)ch == 27) {  // ESC key ASCII value is 27
                printf("Exiting...<br>");
                break;
            }
            
            printf("You pressed: %c (ASCII: %d)<br>", ch, (int)ch);
        }
    }
    
    return 0;
}

Standard Alternative

Since kbhit() is non-standard, here's a portable alternative using standard C −

#include <stdio.h>

int main() {
    char input[100];
    printf("Enter text (type 'quit' to exit):<br>");
    
    while (1) {
        printf("> ");
        if (fgets(input, sizeof(input), stdin) != NULL) {
            // Remove newline character if present
            if (input[0] == 'q' && input[1] == 'u' && 
                input[2] == 'i' && input[3] == 't') {
                printf("Goodbye!<br>");
                break;
            }
            printf("You entered: %s", input);
        }
    }
    
    return 0;
}
Enter text (type 'quit' to exit):
> hello
You entered: hello
> world
You entered: world
> quit
Goodbye!

Key Points

  • kbhit() is non-standard and only works on Windows/DOS systems.
  • It's typically paired with getch() for immediate key reading.
  • For portable code, use standard input functions like fgets() or getchar().
  • Modern applications should avoid platform-specific functions for better portability.

Conclusion

While kbhit() provides immediate keyboard input detection, it's non-standard and should be avoided in portable C programs. Use standard C input functions for better compatibility across different systems.

Updated on: 2026-03-15T10:34:39+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements