I`m trying to make Rock Paper Scissors game in c++.I tested my code on codecademy.com And It worked Properly but when I execute it on codewars.com It gives me this error :
main.cpp:29:1: warning: control may reach end of non-void function [-Wreturn-type]
}
^
This is my code :
#include <string>
#include <iostream>
std::string rps(const std::string& p1, const std::string& p2)
{
if (p1 == "rock" && p2 == "paper") {
return "Player 2 won!";
} else if (p1 == "rock" && p2 == "scissors") {
return "Player 1 won!";
} else if (p1 == "rock" && p2 == "rock") {
return "Draw";
} else if (p1 == "paper" && p2 == "rock") {
return "Player 1 won!";
} else if (p1 == "paper" && p2 == "scissors") {
return "Player 2 won!";
} else if (p1 == "paper" && p2 == "paper") {
return "Draw";
} else if (p1 == "scissors" && p2 == "rock") {
return "Player 2 won!";
} else if (p1 == "scissors" && p2 == "paper") {
return "Player 1 won!";
} else if (p1 == "scissors" && p2 == "scissors") {
return "Draw";
}
}
int main() {
std::cout << rps("rock", "scissors") << "\n";
std::cout << rps("rock", "paper") << "\n";
std::cout << rps("rock", "rock") << "\n";
std::cout << rps("scissors", "paper") << "\n";
std::cout << rps("scissors", "rock") << "\n";
return 1;
}
As already mentioned in the other answer, the parameters
p1
andp2
ofstd::string rps(const std::string& p1, const std::string& p2)
arestd::strings
and can - from the perspective of the compiler - contain any value.Given that there can be a combination of
p1
andp2
for which none of the conditions is true. If you don't return a value from avoid
function (exceptmain
) it will cause undefined behavior.So you either need to throw an exception at that point or return e.g. an empty string.
But it would be better to change the code so that the parameters and return types are enums and the function first checks for the win situations and as a default returns that no one won.
If you really need to use strings as an input you want to verify/convert them outside of your
rps
function with something like that: