在'while'中测试'SDL_PollEvent'的正确方法 [英] The correct way to test 'SDL_PollEvent' in a 'while'

查看:33
本文介绍了在'while'中测试'SDL_PollEvent'的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如手册所说,函数 SDL_PollEvent 如果有未决事件,则返回 1,如果没有可用事件,则返回 0.",这就是为什么我们使用测试 SDL_PollEvent(&e)!=0(其中 eSDL_Event).

但是,如何使用这个测试:!SDL_PollEvent(&e)?它应该可以工作,但显然它会导致一些问题.

这是一个代码示例:

 #include #include int main(int argc, char* args[]){SDL_Init(SDL_INIT_VIDEO);SDL_Window* window = SDL_CreateWindow("你好",SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 100, 100, SDL_WINDOW_SHOWN);SDL_Event e;int 退出=0;而(!退出){//这里测试而 (!SDL_PollEvent(&e)){if (e.type==SDL_QUIT)退出=1;否则 if ( e.type == SDL_KEYDOWN )printf("你好\n");}}SDL_DestroyWindow(窗口);SDL_退出();返回0;}

这段代码应该做的是每次按下一个键时打开一个新窗口并在控制台中打印Hello".此代码在测试 SDL_PollEvent(&e)!=0 中运行良好,但是当我使用测试 !SDL_PollEvent(&e)(但它确实在 while 中输入并毫无问题地处理 SDL_QUIT 事件).
为什么会出现这种行为?

解决方案

while (!SDL_PollEvent(&e))

必须是:

while (SDL_PollEvent(&e))

如果它应该与 SDL_PollEvent(&e) != 0

相同

因为 !SDL_PollEvent(&e) 和调用 while(0)

是一样的

As the manual says, the function SDL_PollEvent "Returns 1 if there is a pending event or 0 if there are none available." , that's why we use the test SDL_PollEvent(&e)!=0 (where e is a SDL_Event).

But, what about use this test: !SDL_PollEvent(&e)? It should work,but apparently it cause some problem.

Here an example of code:

    #include <SDL2/SDL.h>
    #include <stdio.h>

    int main(int argc, char* args[]){
      SDL_Init(SDL_INIT_VIDEO);
      SDL_Window* window =   SDL_CreateWindow("Hello",SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 100, 100,  SDL_WINDOW_SHOWN);
      SDL_Event e;
      int quit=0;
      while(!quit){
          //Here the test
          while (!SDL_PollEvent(&e)){
             if (e.type==SDL_QUIT)
                quit=1;
             else if ( e.type == SDL_KEYDOWN )
                printf( "Hello\n" );
          }
      }
      SDL_DestroyWindow(window);
      SDL_Quit();
      return 0;
   }

What this code should do is open a new window and print "Hello" in the console every time a key is pressed. This code works fine whit the test SDL_PollEvent(&e)!=0 but it doesn't read the SDL_KEYDOWN event when I use the test !SDL_PollEvent(&e) (but it DOES enter in the while and process the SDL_QUIT event without any problem).
Why this behaviour?

解决方案

while (!SDL_PollEvent(&e))

needs to be:

while (SDL_PollEvent(&e))

if it should be the same as SDL_PollEvent(&e) != 0

because !SDL_PollEvent(&e) is the same as calling while(0)

这篇关于在'while'中测试'SDL_PollEvent'的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆