[C/CPP系列知识] Type difference of character literals 和 bool in C and C++
C/C+中的每一个常亮(every literal)都是有类型的,例如10 就是int型的,因此siziof(10)和sizeof(int)是相同的,但是字符型常亮(‘a’)在C和C++中有不同的变量类型。
在C中,‘a’被认为是int形,在C++中,‘a’被认为是char型。
int main() { printf("sizeof('V') = %d sizeof(char) = %d", sizeof('V'), sizeof(char)); return 0; }
结果:
C result – sizeof(‘V’) = 4 sizeof(char) = 1
C++ result – sizeof(‘V’) = 1 sizeof(char) = 1
上述行为也可以体现C++的函数重载
void foo(char c) { printf("From foo: char"); } void foo(int i) { printf("From foo: int"); } int main() { foo('V'); return 0; }
则调用void foo(char c)
3) Types of boolean results are different in C and C++.
// output = 4 in C (which is size of int) printf("%d", sizeof(1==1)); // output = 1 in c++ (which is the size of boolean datatype) cout << sizeof(1==1);