I am trying to compile following code without warnings:
while (window.pollEvent(event))
{
switch (event.type) {
case sf::Event::Closed:
window.close(); break;
case sf::Event::KeyPressed:
if(event.key.code == sf::Keyboard::Escape )
window.close();
if( sf::Keyboard::isKeyPressed( sf::Keyboard::Space ) )
particleSystem.fuel( 200/* * window.getFrameTime() */);
if( sf::Keyboard::isKeyPressed( sf::Keyboard::A ) )
particleSystem.setPosition( --xpos, ypos );
if( sf::Keyboard::isKeyPressed( sf::Keyboard::D ) )
particleSystem.setPosition( ++xpos, ypos );
if( sf::Keyboard::isKeyPressed( sf::Keyboard::W ) )
particleSystem.setPosition( xpos, --ypos );
if( sf::Keyboard::isKeyPressed( sf::Keyboard::S ) )
particleSystem.setPosition( xpos, ++ypos );
if( sf::Keyboard::isKeyPressed( sf::Keyboard::Left ) )
particleSystem.setGravity( --xgrv * 0.1f, ygrv * 0.1f);
if( sf::Keyboard::isKeyPressed( sf::Keyboard::Right ) )
particleSystem.setGravity( ++xgrv * 0.1f, ygrv * 0.1f );
if( sf::Keyboard::isKeyPressed( sf::Keyboard::Up ) )
particleSystem.setGravity( xgrv * 0.1f, --ygrv * 0.1f );
if( sf::Keyboard::isKeyPressed( sf::Keyboard::Down ) )
particleSystem.setGravity( xgrv * 0.1f, ++ygrv * 0.1f );
if( sf::Keyboard::isKeyPressed( sf::Keyboard::G ) )
particleSystem.setGravity( 0.0f, 0.0f );
if( sf::Keyboard::isKeyPressed( sf::Keyboard::P ) )
particleSystem.setPosition( 320.0f, 240.0f );
break;
}
however, I am getting a lot of warnings:
/home/bluszcz/private/repo/deerportal/game.cpp:444: warning: enumeration value 'LostFocus' not handled in switch [-Wswitch]
Which in my it is not an issue, since I am don't need handling all types of the events.
Adding
default:
break;
to my code removes the warnings, however is it a best way to solve this issue?
It depends on what you are trying to achieve. The governing rule is
It is better to be explicit.
Omitting the cases simply makes it look like you forgot some. Being explicit assures subsequent readers of your code that you intended to do nothing for certain events.
In light of that, you have a couple of options:
default:
break;
This suppresses the warning, and makes it clear that you don't intend to handle the other event types here.
List each event type, followed by a break
.
This is also explicit, and has the added bonus that, should you ever add an event type, the compiler will once again warn you that your switch
is incomplete. This can be valuable when you have many switch statements, some of which need to be modified to do something new when an enum value is added.
I would not recommend using a series of if
statements here. A switch
is clearer, reduces the amount of typing, and (as you've seen) can produce better compiler warnings for cases you omitted.