Technology
What is the Difference Between putchar and putch Functions in C?
What is the Difference Between putchar and putch Functions in C?
In C programming, both putchar and putch functions are used to output a single character to the standard output, usually the console. However, they have some notable differences in terms of their usage and availability. This article aims to clarify these differences and help you understand when to use which function.
Standard Function: putchar
putchar is a part of the C standard library, defined in the stdio.h header file. It is a widely recognized and portable function across different compilers and environments.
Prototype:int putchar(int c);Functionality: It takes a single argument, an integer value representing a character, and writes that character to the standard output. It returns the character written as an unsigned char cast to an int or EOF (End of File) on error. Usage:
putchar('A'); // Outputs A
Non-Standard Function: putch
putch is a non-standard function, meaning it is not part of the C standard library. It is commonly found in certain compilers like Turbo C or older versions of MS-DOS. This function is not portable and may not be available in all environments.
Prototype:void putch(int c);Functionality: Similar to putchar, it outputs a single character but it does not return a value (void function). Usage:
putch('A'); // Outputs A
Summary
Standardization
putchar is a standard and portable function across different compilers, whereas putch is compiler-specific and may not be available in all environments.
Return Type
putchar returns the character written or an error indicator (EOF), while putch does not return any value.
For portability and adherence to the standard C programming language, it is highly recommended to use putchar.
Additional Information
The putchar function can output any character from the C character set, including both printable and non-printable characters. On the other hand, the putch function is typically used to display all alphanumeric characters through the standard output device, such as a monitor. Both functions operate by writing a single character at a time to the console.
Examples
Example 1 (Using putchar):
#include stdio.hint main() { putchar('A'); return 0;}
Example 2 (Using putch):
void putch(int c) { // Implementation for Turbo C or MS-DOS versions}void main() { putch('A');}
Conclusion
Understanding the differences between putchar and putch is crucial for writing portable and robust C programs. While both functions perform a similar task, putchar is the preferred and more reliable option. By using putchar, you ensure your code is compatible across different environments and platforms.