zoukankan      html  css  js  c++  java
  • Type difference of character literals in C and C++

      

      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).

    1 int main()
    2 {
    3    printf("sizeof('V') = %d sizeof(char) = %d", sizeof('V'), sizeof(char));
    4    return 0;
    5 }

      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.

     1 #include <iostream>
     2 using namespace std;
     3 
     4 void foo(char c)
     5 {
     6     printf("From foo: char");
     7 }
     8 void foo(int i)
     9 {
    10     printf("From foo: int");
    11 }
    12 
    13 int main()
    14 {
    15     foo('V');
    16     return 0;
    17 }

      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

  • 相关阅读:
    OD: Kernel Vulnerabilities
    newInstance()和new的区别
    原型模式
    工厂模式
    代理模式
    策略模式
    简单工厂模式
    C#操作符的重载
    旅行之舌尖上的中国
    模式和原则[转载]
  • 原文地址:https://www.cnblogs.com/iloveyouforever/p/3445681.html
Copyright © 2011-2022 走看看