在使用C++时,需要考虑一个问题,就是数据类型的选择,用short、int、long还是long long,需要注意是否溢出的问题。而由于使用的环境不同,其数据类型大小存在区别。当年刚学C时,为了最简化使用,不去仔细想,投机取巧全部都用了long,现在想起来好逗比。从来没考虑过数据类型大小的本质规定,今天就来学习一下。
C++中提供了很简单的一个函数sizeof()来快速得到数据类型、变量的大小,这样就可以快速找到合适的数据类型了。
int i = 0;
cout << "int is " << sizeof(int) << " bits." << endl;
cout << "i is " << sizeof(i) << " bits." << endl;
cout << "i is " << sizeof i << " bits." << endl;
结果如下:
sizeof()获取变量大小有两种方法,但是如果是数据类型比如int,只能使用括号。一般使用习惯都是使用括号形式。 头文件climits(老式实现中为limits.h)中包含了关于数据类型大小的定义。
#define CHAR_BIT 8 /* number of bits in a char */ #define SCHAR_MIN (-128) /* minimum signed char value */ #define SCHAR_MAX 127 /* maximum signed char value */ #define UCHAR_MAX 0xff /* maximum unsigned char value */
#ifndef _CHAR_UNSIGNED #define CHAR_MIN SCHAR_MIN /* mimimum char value */ #define CHAR_MAX SCHAR_MAX /* maximum char value */ #else #define CHAR_MIN 0 #define CHAR_MAX UCHAR_MAX #endif /* _CHAR_UNSIGNED */
#define MB_LEN_MAX 5 /* max. # bytes in multibyte char */ #define SHRT_MIN (-32768) /* minimum (signed) short value */ #define SHRT_MAX 32767 /* maximum (signed) short value */ #define USHRT_MAX 0xffff /* maximum unsigned short value */ #define INT_MIN (-2147483647 - 1) /* minimum (signed) int value */ #define INT_MAX 2147483647 /* maximum (signed) int value */ #define UINT_MAX 0xffffffff /* maximum unsigned int value */ #define LONG_MIN (-2147483647L - 1) /* minimum (signed) long value */ #define LONG_MAX 2147483647L /* maximum (signed) long value */ #define ULONG_MAX 0xffffffffUL /* maximum unsigned long value */ #define LLONG_MAX 9223372036854775807i64 /* maximum signed long long int value */ #define LLONG_MIN (-9223372036854775807i64 - 1) /* minimum signed long long int value */ #define ULLONG_MAX 0xffffffffffffffffui64 /* maximum unsigned long long int value */ 可以看到各数据类型的位数、最大最小值的宏定义。我们可以直接使用这些宏定义来查看数据类型的大小信息。下面是一个很简单的例子:
#include <iostream> #include <climits>
using namespace std;
int main(int argc, char ** argv) { cout << "int is " << sizeof(int) << " bits." << endl; cout << "short is " << sizeof(short) << " bits." << endl; cout << "long is " << sizeof(long) << " bits." << endl; cout << "long long is " << sizeof(long long) << " bits." << endl; cout << "char is " << sizeof(char) << " bits." << endl;
cout << endl << "Maximum and Minimum values: " <<endl; cout << "int: " << INT_MAX << " and " << INT_MIN << endl; cout << "short: " << SHRT_MAX << " and " << SHRT_MIN << endl; cout << "long: " << LONG_MAX << " and " << LONG_MIN <<endl; cout << "long long: " << LLONG_MAX << " and " << LLONG_MIN <<endl; cout << "char: " << CHAR_MAX << " and " << CHAR_MIN <<endl;
system("pause"); return 0;
} 通过这些宏定义可以直接查看数据类型的大小信息,再也不用每次都去查大小了。结果如下:
|