對變量類型定義規範的一些說明,更宏觀的規範可參見完善中的《版本開發中項目、工程與代碼規範》: 點擊打開鏈接
開發中經常碰到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.csdn.net/lezhiyong