Lots of typedefs in windows.h

I am new to programming in the Windows environment. The language I use is C. More specifically, I try to manipulate COM-ports on Windows manually (without special libraries, only WinAPI functions).

My question concerns the presence lots of typedef’s in windows.h. What purpose do they serve?

Is it OK to mix bool, BOOL, unsigned int and WORD, for example, in one source file (from the points of view either coding style or effectiveness), or I need some kind of standardization (use BOOL instead of bool everywhere and so on)?

The typical example of function with different parameter types in my code is this:

bool ConfigureDCB(  HANDLE  hp_ComPort,
                    bool    bUseCurrentSettings,
                    DWORD   dwBaudRate,
                    BOOL    bParityCheck,
                    BYTE    byteSize,
                    BYTE    parityMode,
                    BYTE    stopBits    )

There are both BOOL and bool types among the function parameters. The first one is used exactly as prescribed in header file (its value is set directly to a BOOL member of structure), and the second one (and function return type as well) is used only as part of program logic:



Windows headers are using BOOL, BYTE, WORD, DWORD etc. for historical reasons.

WORD was defined when computers used 16 bit words. Nowadays “words” are often 64 bit, but nobody uses the term “words” anymore. So when you see a type WORD, you know “aha, that’s Windows, and it means uint16_t”. Same with DWORD, which was a double word (32 bit) when computers used 16 bit words; nowadays reading “DWORD” means “Windows, uint32_t”. BYTE is basically a synonym for “uint8_t”.

HANDLE is an abstract type. BOOL is slightly dangerous: It is not the same as bool. It’s almost the same, but not quite the same. I wouldn’t make any bets that BOOL and bool use the same number of bits, for example.

It’s up to you, really. Personally, I think a user of your function should be confronted with Windows weirdness as little as possible, so I’d give the parameters the types HANDLE, bool, and int. But that’s just me.

The purpose they serve is to give developers using those headers certainty about what the types really are. Some of the normal C types vary from one compiler or architecture to another.

The impact of mixing types on effectiveness is if you introduce unexpected type conversions, so it’s a potential source of bugs and other suboptimalities.

The impact on style is consistency. For example, mixing is consistent if you only use the Microsoft types to call their APIs, and use the normal types for your own code. Mixing that goes deeper than that is probably bad style because it’s inconsistent, but there may be exceptions depending on how you think about categories in your code.


Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *