的时候偶然间发现了书中源代码潜在的错误

villager 2003-09-29 10:47:40
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage (&msg) ;
DispatchMessage (&msg) ;
}
return msg.wParam ;

上面这行代码是该书中常用的消息处理方式。当GetMessage函数调用失败的时候会返回-1。这个时候while循环的条件就成了:

while(-1) ;

编译出来的应用程序会出现致命错误!大家来想一想怎么来去掉这个潜在的错误。
...全文
76 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
晨星 2003-09-30
  • 打赏
  • 举报
回复
不管怎么说,这确实是个问题,因为既然是错误,最好做特殊处理,以免引起更严重的问题。
我同意jeckyz(深圳)的方案。
XBug 2003-09-30
  • 打赏
  • 举报
回复
关注
fireseed 2003-09-30
  • 打赏
  • 举报
回复
to villager(为什么我这么绝顶聪明 却还是菜鸟?) 有技术问题可以讨论,但请不要骂人,说脏话。

我不知道你的编译环境是怎么设置的……

/* 以下代码在VC.net环境下编译通过,并正常运行 */
/* Creamdog保留所有权力 */

#include <iostream>
using namespace std;

void main( void )
{
while( -1 )
{
}
system( "pause" );
}
fireseed 2003-09-30
  • 打赏
  • 举报
回复
to villager(为什么我这么绝顶聪明 却还是菜鸟?) 有技术问题可以讨论,但请不要骂人,说脏话。

我不知道你的编译环境是怎么设置的……

/* 以下代码在VC.net环境下编译通过,并正常运行 */
/* Creamdog保留所有权力 */

#include <iostream>
using namespace std;

void main( void )
{
while( -1 )
{
}
system( "pause" );
}
villager 2003-09-30
  • 打赏
  • 举报
回复
别的环境不知道,Win32下的HelloWin一定会出错。这是MSDN上就说过的。严禁直接使用GetMessage()放在while里的。
villager 2003-09-30
  • 打赏
  • 举报
回复
试一试while(-1)会出现什么结果!~!!!!

不试就没有发言权。那个奶奶狗。我管你是不是版主。
jeckyz 2003-09-30
  • 打赏
  • 举报
回复
// Start the message loop.

while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}

fireseed 2003-09-30
  • 打赏
  • 举报
回复
请villager(为什么我这么绝顶聪明 却还是菜鸟?) 自重,切莫引起争吵

谢谢合作!
fireseed 2003-09-30
  • 打赏
  • 举报
回复
while(-1)

我想不出有什么问题……

while后面跟的是一个bool值,而按照C++语义,标准数据类型转换规则,从其它类型转为bool时,0是false,非0是true
villager 2003-09-30
  • 打赏
  • 举报
回复
觉得不对就直说。

别像个太监一样阴阳快气的
villager 2003-09-30
  • 打赏
  • 举报
回复
楼上那位什么意思???
feiyingw 2003-09-30
  • 打赏
  • 举报
回复
为自作聪明干杯
villager 2003-09-30
  • 打赏
  • 举报
回复
VC6有问题,可能是编译器的问题。
skywinner 2003-09-29
  • 打赏
  • 举报
回复
GetMessage does not remove WM_PAINT messages from the queue. The messages remain in the queue until processed.

Note that the function return value can be TRUE, FALSE, or -1. Thus, you should avoid code like this:

while (GetMessage( lpMsg, hWnd, 0, 0)) ...


The possibility of a -1 return value means that such code can lead to fatal application errors.

上面是delphi里的帮助文件中的
villager 2003-09-29
  • 打赏
  • 举报
回复
while (GetMessage(&msg, NULL, 0, 0) > 0)

怎么样?

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧