C#和C++中char型別的區別
對於char,這個字元型別。我們一般都認為就是一個位元組。今天在仔細比較發現,C#的char和C++的char是有區別的。
1.首先來看C#中char佔多大空間
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(sizeof(char));
Console.Read();
}
}
}
居然是返回2.也就是說兩個位元組。
2. 在C++中呢?
#include <iostream>
using namespace std;
int main()
{
cout << sizeof(char)<<endl;
return 0;
}
這裡看到的結果是顯示為1個位元組
但是同時,我又想起來,C++裡面還有另外一個char型別,也就是所謂的wchar_t,通常用來表示unicode char,它的空間是多少呢?
#include <iostream>
using namespace std;
int main()
{
cout << sizeof(wchar_t)<<endl;
return 0;
}
3. 那麼,是不是說C#中的char都是表示unicode字元的呢?
沒錯,就是這樣. 如此才能解釋得通嘛
char 關鍵字用於宣告下表所示範圍內的 Unicode 字元。Unicode 字元是 16 位字元,用於表示世界上大多數已知的書面語言。
型別 |
範圍 |
大小 |
.NET Framework 型別 |
---|---|---|---|
char |
U+0000 到 U+ffff |
16 位 Unicode 字元 |
4. 題外話:SQL Server 中的字元型別
我還想到,在SQL Server的型別系統中有下面幾個字元型別,大家也要有所比較
定長 | char |
定長(unicode) | nchar |
變長 | varchar |
變長(unicode) | nvarchar |
也就是說,在SQL Server中也是明確地區分unicode和非unicode的