@Jesper: I could, but i normally have bad experiences with 'else's, they'll just not work for me sometimes, so I just usually play it safe and go with another 'if.'
Not trying to be rude, but that sounds like you should spend some more time with a good C++ book.
The
else statement does
exactely what its name implies; if the main (
if) branch is not taken the
else branch is. There is no magic or ambiguity there.
It seems the 'if' statement you're wanting to add just adds another comparison.
Let's compare.
Here's how you wrote the function:
bool typeText(sf::Clock & clock, sf::String & stringSF, sf::Event & event, std::string & string)
{
bool finished = false;
if (event.type == sf::Event::TextEntered && clock.getElapsedTime() >= sf::milliseconds(120)
&& event.text.unicode != '\b' && event.text.unicode != '\r')
{
clock.restart();
stringSF.insert(stringSF.getSize(), event.text.unicode);
}
if (event.type == sf::Event::TextEntered && event.text.unicode == '\b' && clock.getElapsedTime() >= sf::milliseconds(100)
&& stringSF.getSize() != 0)
{
clock.restart();
string.erase(stringSF.getSize() - 1, 1);
stringSF = string;
}
if (event.type == sf::Event::TextEntered && event.text.unicode == '\r')
{
clock.restart();
string = stringSF;
finished = true;
}
return finished;
}
In the case where the function is called with an event where .type
is sf::Event::TextEntered I count
3 comparisons.
In the case where the function is called with an event where .type
is not sf::Event::TextEntered I count
3 comparisons.
Here's how I'd write the function (at least regarding what we are discussing here):
bool typeText(sf::Clock& clock, sf::String& stringSF, sf::Event& event, std::string& string)
{
if (event.type != sf::Event::TextEntered)
return false;
bool finished = false;
if (clock.getElapsedTime() >= sf::milliseconds(120) && event.text.unicode != '\b' && event.text.unicode != '\r') {
clock.restart();
stringSF.insert(stringSF.getSize(), event.text.unicode);
} else if (event.text.unicode == '\b' && clock.getElapsedTime() >= sf::milliseconds(100) && stringSF.getSize() != 0) {
clock.restart();
string.erase(stringSF.getSize() - 1, 1);
stringSF = string;
} else if (event.text.unicode == '\r') {
clock.restart();
string = stringSF;
finished = true;
}
return finished;
}
In the case where the function is called with an event where .type
is sf::Event::TextEntered I count
1 comparison.
In the case where the function is called with an event where .type
is not sf::Event::TextEntered I count
1 comparison.
Also consider the fact of the many fewer comparisons of all the stuff that is
not event.type due to the use of
else if.