I was watching a tutorial that says that we first need to check if any direction key was pressed, and only then we check which key was pressed, like this:

while( running == true )
	{
		while( SDL_PollEvent(&event) )
		{
			if ( event.type == SDL_KEYDOWN ) //checking if any key was pressed
			{
				switch( event.key.keysym.sym ) //checking for specific 
				{
				case SDLK_UP: yC -= 10; break; // yC -coordinates of a surface
				case SDLK_DOWN: yC +=10; break;
				}
			}
			else
				if ( event.type == SDL_QUIT )
				{
					running = false;
				}
		}

But then i tried to do it wihouth checking if any key was pressed and just jump to the specific key that was pressed:

while( running == true )
	{
		while( SDL_PollEvent(&event) )
		{
			if ( event.key.keysym.sym == SDLK_UP )
			{
				yC -= 10;
			}
			else
				if ( event.key.keysym.sym == SDLK_DOWN )
				{
					yC += 10;
				}
			else
				if ( event.type == SDL_QUIT )
				{
					running = false;
				}
		}

And the thing is that for some reason when i use the tutorial method it works just fine, but when i use my method the surface moves when i press the button and when i let go of it. Why do we even need to check if any key was pressed?

I was watching a tutorial that says that we first need to check if any direction key was pressed, and only then we check which key was pressed, like this:

But then i tried to do it wihouth checking if any key was pressed and just jump to the specific key that was pressed:

And the thing is that for some reason when i use the tutorial method it works just fine, but when i use my method the surface moves when i press the button and when i let go of it. Why do we even need to check if any key was pressed?

if ( event.type == SDL_KEYDOWN ) //checking if any key was pressed

The comment "checking if any key was pressed" is misleading. Really it's checking if the specific key event we're responding to is a "key down" event. Without this line, your code executes on all key events, including "key up"--this is why it behaves the way you describe.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.