先看看如下代码:
In C:
#include <stdio.h>
int main(){
printf("Size of char : %d\n",sizeof(char));
return 0;
}
In C++:
#include <iostream>
int main(){
std::cout<<"Size of char : "<<sizeof(char)<<"\n";
return 0;
}
毫无疑问,输出的是:Size of char :1
我们知道在character代表的是‘a','b','c','|',....这样的东西,所以我只是将上面的代码稍微修改了一下:
In C:
#include <stdio.h>
int main(){
char a = 'a';
printf("Size of char : %d\n",sizeof(a));
printf("Size of char : %d\n",sizeof('a'));
return 0;
}
输出:
Size of char : 1
Size of char : 4
In C++:
#include <iostream>
int main(){
char a = 'a';
std::cout<<"Size of char : "<<sizeof(a)<<"\n";
std::cout<<"Size of char : "<<sizeof('a')<<"\n";
return 0;
}
输出:
Size of char : 1
Size of char : 1
所以问题来了,为什么sizeof('a')在c和c++中返回的值不同呢?
解释如下:
在c中character类型,如’a'其实是是一个int,而在C++中则是一个char,所以一个是sizeof(int),一个是sizeof(char)。这样就好理解了。
下面是相关英文解释:
In C, character literals such as 'a' have type int, and thus sizeof('a') is equal to sizeof(int).
In C++, character literals have type char, and thus sizeof('a') is equal to sizeof(char).
This difference can lead to inconsistent behavior in some code that is compiled as both C and C++.
memset(&i, 'a', sizeof('a')); // Questionable code
In practice, this is probably not much of a problem, since character constants are implicitly converted to type int when they appear within expressions in both C and C++.
参考:http://david.tribble.com/text/cdiffs.htm#C99-char-literal(C与C++的区别,很详细)
http://stackoverflow.com/questions/2172943/size-of-character-a-in-c-c