VC中易犯的错误

来源:互联网 发布:淘宝扣子 编辑:程序博客网 时间:2024/06/05 11:06
在这里面总结一下VC中易常犯的错误.
一/前两天过一个串口的通迅程序,有如下一段代码:
HANDLE hCom=CreateFile(......);(构造函数里面将hCom=NULL)
if(hCom)
{
//如果hCom有值,则说明创建成功
}
else
{
//没成功
}
看上去好像没什么问题,其实错的很彻底.
Windows via c/c++中有这样一段话:

If CreateFile succeeds in creating or opening a file or device, the handle of the file or device is returned. If CreateFile fails, INVALID_HANDLE_VALUE is returned.


Note 

Most Windows functions that return a handle return NULL when the function fails. However, CreateFile returns INVALID_HANDLE_VALUE (defined as –1) instead. I have often seen code like this, which is incorrect:

HANDLE hFile = CreateFile(...);
if (hFile == NULL) {
// We'll never get in here
} else {
// File might or might not be created OK
}

Here's the correct way to check for an invalid file handle:

HANDLE hFile = CreateFile(...);
if (hFile == INVALID_HANDLE_VALUE) {
// File not created
} else {
// File created OK
}

原创粉丝点击