对变量类型定义规范的一些说明,更宏观的规范可参见完善中的《版本开发中项目、工程与代码规范》: 点击打开链接
开发中经常碰到BOOL,bool,char, signed char,unsigned char, BYTE,CHAR,WORD,short , unsigned short,DWORD,int , long long ,float,double,__int64 等整型、浮点型、字符型。
有些类型是windows对基本数据的重定义,如:
DWORD:typedef unsigned long DWORD
WORD:typedef unsigned short WORD
BYTE: typedef unsigned char BYTE
有些数据类型的大小随编译器和平台而不同:
如long与int所占字节数由于操作系统或编译器的不同而变化。
16位系统:long是4字节,int是2字节
32位系统:long是4字节,int是4字节
64位系统:long是8字节,int是4字节
那么对于如下代码:
for(int i = 0;i<65540;i++)
{
….
}
可能在不同的平台上得到不同的结果。如果这个代码是在 16 位机器上运行,那么得到的结果与 32 位机器上可能不同。
而有些类型是有符号类型还是无符号类型取决于编译器:
对于char,一些c实现把char当做有符号类型signedchar(-128-127),一些当成无符号类型unsigned char(0-255)。
所以当char转化为其他类型的时候(比如int),结果会因编译器而不同。
或者如果用char做字段右移位操作时候,左边填充的是0还是1也取决于编译器。
并最好把存放cha型的变量值限制在有符号类型(-128-127)和无符号类型(0-255)的交集中。如果要算术运行,使用unsigned char 或signed char 《c与指针》p30
没有必要这么多类型名称使用都使用在工程中,可以使用typedef定义精确定义数据大小的类型,变量类型调整也很好控制,这在网络传输、文件读写操作、跨平台开发保持数据的一致性很重要,当然在工程内部也要养成这个习惯。
typedef重定义数据类型时,不要使用int8、int32等通用的名称,如果两个工程中都使用typedef定义了int32,但工程a的定义为typedef signed int int32,而工程b定义为typedef long int32;那么a与b互相调用时候就会发生定义冲突的问题。
可使用int8_(特定标识X)或(特定标识X)_int8 等能区别其他工程中的类型定义的名字:
如用typedefd定义的int8_X,uint8_X ,int16_X ,uint16_X,int32_X,uint32_X,float32_X,float64_X,int64_X,uint64_X类型可满足项目的开发:
int8_X 代替char, signed char
uint8_X 代替 unsigned char
int16_X 代替signed short
uint16_X 代替unsigned shor,WORD
int32_X 代替int, signed int, long, signed long,
uint32_X 代替 unsigned int, unsigned long,DWORD
float32_X 代替 float
float64_X 代替double
int64_X 代替long long
uint64_X 代替unsigned long long
最后参见google开源项目webrtc的类型定义头文件typedefs.h中的规范:
#if !defined(_MSC_VER)
#include <stdint.h>
#else
// Define C99 equivalent types.
// Since MSVC doesn't include these headers, we have to write our own
// version to provide a compatibility layer between MSVC and the WebRTC
// headers.
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
typedef signed long long int64_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;
#endif
#if defined(WIN32)
typedef __int64 WebRtc_Word64;
typedef unsigned __int64 WebRtc_UWord64;
#else
typedef int64_t WebRtc_Word64;
typedef uint64_t WebRtc_UWord64;
#endif
typedef int32_t WebRtc_Word32;
typedef uint32_t WebRtc_UWord32;
typedef int16_t WebRtc_Word16;
typedef uint16_t WebRtc_UWord16;
typedef char WebRtc_Word8;
typedef uint8_t WebRtc_UWord8;
// Define endian for the platform
#define WEBRTC_LITTLE_ENDIAN
#elif defined(WEBRTC_TARGET_MAC_INTEL)
#include <stdint.h>
typedef int64_t WebRtc_Word64;
typedef uint64_t WebRtc_UWord64;
typedef int32_t WebRtc_Word32;
typedef uint32_t WebRtc_UWord32;
typedef int16_t WebRtc_Word16;
typedef char WebRtc_Word8;
typedef uint16_t WebRtc_UWord16;
typedef uint8_t WebRtc_UWord8;
// Define endian for the platform
#define WEBRTC_LITTLE_ENDIAN
#else
#error "No platform defined for WebRTC type definitions (typedefs.h)"
#endif
来源:http://blog.youkuaiyun.com/lezhiyong