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;
}
I'm going to assume the question you wanted to ask -- but didn't write down in your question -- is "why do I get this error message?"
Well, there's a path through
rps()that does not return a value. You, as a person, might know thatrps()is always called only with "rock", "paper", or "scissors", but the compiler does not. In that case, what shouldrps()return if you call it asrps(std::string("stone"),std::string("knife"))? It has to return something (or throw an exception) because you've promised it would return a std::string.There's various things you might do:
Note that the compiler is helping you here. Why does flowing off the end of a non-void function without returning a value not produce a compiler error?