17

C++整数常量的前缀和后缀

 3 years ago
source link: http://developer.51cto.com/art/202007/621298.htm
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

3iIZjef.jpg!web

在C/C++中,整数常量可以加上不同的前缀,表示不同的进制:

  • 十进制:不带前缀,默认表示为十进制
  • 八进制:0 表示八进制
  • 十六进制:0x 或 0X 表示十六进制

整数常量还可以加上不同的后缀,表示不同的数据类型:

  • 无符号:U
  • 长整数:L

示例代码如下:

#include <iostream> 
using namespace std; 
int main() 
{ 
    int x = 666; // 十进制 
    int y = 020; // 八进制 
    int z = 0XF; // 十六进制 
    cout << "x:" << x << endl; 
    cout << "y:" << y << endl; 
    cout << "z:" << z << endl; 
   
    auto a = 666;   // 整数 
    auto b = 666U;  // 无符号整数 
    auto c = 666L;  // 长整数 
    auto d = 666UL; // 无符号长整数 
    cout << "type(a): " << typeid(a).name() << endl; 
    cout << "type(b): " << typeid(b).name() << endl; 
    cout << "type(c): " << typeid(c).name() << endl; 
    cout << "type(d): " << typeid(d).name() << endl; 
   
    return 0; 
} 

其中,typeid().name(),可以用来返回变量的数据类型。运行结果如下:

MRRzq2V.jpg!web

typeid().name() 返回的是变量数据类型的缩写,对应关系如下图所示。

aMrAJn2.jpg!web

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK