Type difference of character literals in C and C++
2013-11-27 14:50
316 查看
Every literal (constant) in C/C++ will have a type information associated with it.
In both C and C++, numeric literals (e.g. 10) will have int as their type. It means sizeof(10) and sizeof(int) will return same value.
However, character literals (e.g. ‘V’) will have different types, sizeof(‘V’) returns different values in C and C++. In C, a character literal is treated as int type where as in C++, a character literal is treated as char type (sizeof(‘V’) and sizeof(char) are same in C++ but not in C).
int main() { printf("sizeof('V') = %d sizeof(char) = %d", sizeof('V'), sizeof(char)); return 0; }
Result of above program:
C result – sizeof(‘V’) = 4 sizeof(char) = 1
C++ result – sizeof(‘V’) = 1 sizeof(char) = 1
Such behaviour is required in C++ to support function overloading.
An example will make it more clear. Predict the output of the following C++ program.
#include <iostream> using namespace std; void foo(char c) { printf("From foo: char"); } void foo(int i) { printf("From foo: int"); } int main() { foo('V'); return 0; }
The compiler must call void foo(char);
since ‘V’ type is char.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
转载请注明:http://www.cnblogs.com/iloveyouforever/
2013-11-27 14:50:03
相关文章推荐
- [C/CPP系列知识] Type difference of character literals 和 bool in C and C++
- C++ difference of keywords 'typename' and 'class' in templates
- type dedution and reference collapse in c++ 11(works vc++ 2013)
- The difference of static, readonly and const in C#
- common and different of final in java and const in C++
- c++ class forward declaration and invalid use of incomplete type
- Virtual method and base-type pointer make polymorphism in C++
- 内存分配与shallow and deep cpoying of objects in C++
- Use the unsinged type as operands of shift operator in C language
- What are the differences between a pointer variable and a reference variable in C++?
- Difference between parseInt and valueOf in java?
- Java Tip 27: Typesafe constants in C++ and Java
- Difference between prop and attr in different version of jquery
- 海洋工作室——网站建设专家:The version of SQL Server in use does not support datatype datetime2 and the Entity Framework.
- 《Description of CWnd derived MFC objects and multithreaded applications in Visual C++》译文
- result of += in C and C++
- type conversion of array and pointer in C(2)
- What are the differences between a pointer variable and a reference variable in C++?
- How to do run-time (or explicit) linking of C++ plug-in components and objects
- Difference of px, dp, dip and sp in android