putwchar() function in C/C++

The putwchar() function in C is used to write a wide character to the standard output (stdout). It is the wide character equivalent of the putchar() function and is defined in the <wchar.h> header file.

Syntax

wint_t putwchar(wchar_t wc);

Parameters

  • wc − The wide character to be written to stdout

Return Value

  • On success: Returns the wide character that was written
  • On failure: Returns WEOF and sets an error indicator

Example 1: Writing Single Wide Character

This example demonstrates writing a single wide character to stdout −

#include <stdio.h>
#include <wchar.h>
#include <locale.h>

int main() {
    setlocale(LC_ALL, "");
    
    wchar_t ch = L'A';
    wprintf(L"Character: ");
    putwchar(ch);
    wprintf(L"\n");
    
    return 0;
}
Character: A

Example 2: Writing Multiple Wide Characters

This example shows how to use putwchar() in a loop to print multiple characters −

#include <stdio.h>
#include <wchar.h>
#include <locale.h>

int main() {
    setlocale(LC_ALL, "");
    
    wprintf(L"Characters: ");
    for (wchar_t i = L'a'; i <= L'e'; i++) {
        putwchar(i);
        putwchar(L' ');
    }
    wprintf(L"\n");
    
    return 0;
}
Characters: a b c d e 

Example 3: Error Checking

This example demonstrates proper error checking with putwchar()

#include <stdio.h>
#include <wchar.h>
#include <locale.h>

int main() {
    setlocale(LC_ALL, "");
    
    wchar_t ch = L'X';
    wint_t result = putwchar(ch);
    
    if (result == WEOF) {
        wprintf(L"Error writing character\n");
    } else {
        wprintf(L"\nSuccessfully wrote character: %lc\n", result);
    }
    
    return 0;
}
X
Successfully wrote character: X

Key Points

  • Always call setlocale() before using wide character functions
  • Use L prefix for wide character literals
  • Check return value for error handling
  • Use wprintf() for wide character formatted output

Conclusion

The putwchar() function provides a simple way to output wide characters to stdout. It supports Unicode characters and is essential for internationalization in C programs.

Updated on: 2026-03-15T12:47:53+05:30

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements