wchar_t
- C course
- Advanced
- Lesson 62/83
- 5 min
Learn wide characters with wchar_t.
wchar_t
wchar_t is a wide character type; it stores each character as a single integer. It is defined in <wchar.h>. On Linux it is usually 4 bytes; it can hold a single code point directly.
A wide character literal is written L'A'; a wide string is L"Merhaba". ASCII characters have the same value in char and wchar_t: (int)L'A' also returns 65. sizeof(wchar_t) is platform-dependent; portable code prints it with %zu.
Size and value
sizeof(wchar_t) gives the type size at compile time; on Linux x86-64 it is 4, on Windows it is 2. That is why portable output needs %zu.
To print a wide character's value you write printf("%d", (int)L'A');. Since 'A' is ASCII, L'A' also carries the value 65. There is also wprintf for printing wide characters; in this lesson we stick to printf for the values to avoid confusion.
Practice wchar_t size and value
Print the size of wchar_t with printf("wchar_t: %zu\n", sizeof(wchar_t));. Print the value of L'A' with printf("değer: %d\n", (int)L'A');. Add the <wchar.h> header.
Starter code
#include <stdio.h>
#include <wchar.h>
// Print wchar_t size with sizeof
// Print L'A' value with (int) cast as %d
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <wchar.h>
int main(void) {
printf("wchar_t: %zu\n", sizeof(wchar_t));
printf("değer: %d\n", (int)L'A');
return 0;
}Expected output
wchar_t: 4 değer: 65
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match wchar_t concepts
| Term | Meaning |
|---|---|
wchar_t |
Wide character |
L'A' |
Wide char literal |
L"..." |
Wide string |
sizeof |
Gives size |
2 What is the value of L'A'?
- 0
- 65 Correct answer
- 97
- 4
Explanation: L'A' carries the ASCII value of 'A': 65.
3 Wide character literal
wchar_t c = L'____';
wchar_t c = L'A';
Explanation: L'A' is a wide character literal.