How to initialize a wchar_t variable?

Yishu Fang picture Yishu Fang · Oct 21, 2012 · Viewed 29.3k times · Source

I am reading the book: C: In a Nutshell, and after reading the section Character Sets, which talks about wide characters, I wrote this program:

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

int main() {
  wchar_t wc = '\x3b1';
  wprintf(L"%lc\n", wc);
  return 0;
}

I then compiled it using gcc, but gcc gave me this warning:

main.c:7:15: warning: hex escape sequence out of range [enabled by default]

And the program does not output the character α (whose unicode is U+03B1), which is what I wanted it to do.

How do I change the program to print the character α?

Answer

David Ranieri picture David Ranieri · Oct 21, 2012

This works for me

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

int main(void) {
  wchar_t wc = L'\x3b1';

  setlocale(LC_ALL, "en_US.UTF-8");
  wprintf(L"%lc\n", wc);
  return 0;
}