初学C/C++,char, wchar_t, TCHAR, ACHAR, _T()这几个类型的差异和联系曾经让我很是头疼,在此做一下简单的归纳总结,希望能给各位刚入门的菜菜们一点帮助。
char :
单字节变量类型,最多表示256个字符,在ANSI C中包括:26 lowercase letters, 26 uppercase letters, 10 digits, 32 symbols, 33 control codes, and a space, for a total of 128 codes.
wchar_t :
宽字节变量类型,用于表示Unicode字符,它实际定义在<string.h>里:typedef unsigned short wchar_t。
定义宽字节类型方法如下:
wchar_t c = `A' ;
wchar_t * p = L"Hello!" ;
wchar_t a[] = L"Hello!" ; 其中,宽字节类型每个变量占用2个字节,故上述数组a的sizeof(a) = 14。
TCHAR / _T( ) :
TCHAR.H provides a set of alternative names for the normal run-time library functions requiring string parameters (for example, _tprintf and _tcslen). These are sometimes referred to as "generic"function names because they can refer to either the Unicode or non-Unicode versions of the functions. TCHAR.H also solves the problem of the two character data types with a new data type named TCHAR.
如果在程序中既包括ANSI又包括Unicode编码,需要包括头文件tchar.h。TCHAR是定义在该头文件中的宏,它视你是否定义了_UNICODE宏而定义成:
定义了_UNICODE: typedef wchar_t TCHAR ;
没有定义_UNICODE: typedef char TCHAR ;
_T( )也是定义在该头文件中的宏,视是否定义了_UNICODE宏而定义成:
定义了_UNICODE: #define _T(x) L##x
没有定义_UNICODE: #define _T(x) x
注意:如果在程序中使用了TCHAR,那么就不应该使用ANSI的strXXX函数或者Unicode的wcsXXX函数了,而必须使用tchar.h中定义的_tcsXXX函数。
char :
单字节变量类型,最多表示256个字符,在ANSI C中包括:26 lowercase letters, 26 uppercase letters, 10 digits, 32 symbols, 33 control codes, and a space, for a total of 128 codes.
wchar_t :
宽字节变量类型,用于表示Unicode字符,它实际定义在<string.h>里:typedef unsigned short wchar_t。
定义宽字节类型方法如下:
![](https://i-blog.csdnimg.cn/blog_migrate/cbef093dcc044b2793832001e2365e43.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/cbef093dcc044b2793832001e2365e43.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/cbef093dcc044b2793832001e2365e43.gif)
TCHAR / _T( ) :
TCHAR.H provides a set of alternative names for the normal run-time library functions requiring string parameters (for example, _tprintf and _tcslen). These are sometimes referred to as "generic"function names because they can refer to either the Unicode or non-Unicode versions of the functions. TCHAR.H also solves the problem of the two character data types with a new data type named TCHAR.
如果在程序中既包括ANSI又包括Unicode编码,需要包括头文件tchar.h。TCHAR是定义在该头文件中的宏,它视你是否定义了_UNICODE宏而定义成:
定义了_UNICODE: typedef wchar_t TCHAR ;
没有定义_UNICODE: typedef char TCHAR ;
_T( )也是定义在该头文件中的宏,视是否定义了_UNICODE宏而定义成:
定义了_UNICODE: #define _T(x) L##x
没有定义_UNICODE: #define _T(x) x
注意:如果在程序中使用了TCHAR,那么就不应该使用ANSI的strXXX函数或者Unicode的wcsXXX函数了,而必须使用tchar.h中定义的_tcsXXX函数。
以strcpy函数为例子,总结一下: