I want to write a TicTacToe program with 2 players (I am doing an exercise from the Jumping into C++
). The syntax below does not have any errors, but let's say i input 1 or 2, the program just exits without any errors or any results. Here is the code that i came up with:
#include <iostream>
using namespace std;
int board_pos;
int main()
{
cout << "Enter => 1 for X; 2 for O:" << endl;
enum TTT_Board{topLeft, topMid, topRight, middleLeft, middleMid, middleRight, botLeft, botMid, botRight};
cout << "-------" << endl;
cout << "|" << topLeft << "|" << topMid << "|" << topRight << "|" << endl; /* Top cells of the board */
cout << "-------" << endl;
cout << "|" << middleLeft << "|" << middleMid << "|" << middleRight << "|" << endl;
cout << "-------" << endl;
cout << "|" << botLeft << "|" << botMid << "|" << botRight << "|" << endl;
cout << "-------" << endl;
if (board_pos == 0){
switch (board_pos) {
case topLeft:
cout << " " << endl;
break;
case topMid:
cout << " " << endl;
break;
case topRight:
cout << " " << endl;
break;
case middleLeft:
cout << " " << endl;
break;
case middleMid:
cout << " " << endl;
break;
case middleRight:
cout << " " << endl;
break;
case botLeft:
cout << " " << endl;
break;
case botMid:
cout << " " << endl;
break;
case botRight:
cout << " " << endl;
break;
default:
break;
}
}
else if (board_pos == 1)
{
switch (board_pos) {
case topLeft:
cout << "X" << endl;
break;
case topMid:
cout << "X" << endl;
break;
case topRight:
cout << "X" << endl;
break;
case middleLeft:
cout << "X" << endl;
break;
case middleMid:
cout << "X" << endl;
break;
case middleRight:
cout << "X" << endl;
break;
case botLeft:
cout << "X" << endl;
break;
case botMid:
cout << "X" << endl;
break;
case botRight:
cout << "X" << endl;
break;
default:
break;
}
}
else if (board_pos == 2)
{
switch (board_pos) {
case topLeft:
cout << "O" << endl;
break;
case topMid:
cout << "O" << endl;
break;
case topRight:
cout << "O" << endl;
break;
case middleLeft:
cout << "O" << endl;
break;
case middleMid:
cout << "O" << endl;
break;
case middleRight:
cout << "O" << endl;
break;
case botLeft:
cout << "O" << endl;
break;
case botMid:
cout << "O" << endl;
break;
case botRight:
cout << "O" << endl;
break;
default:
break;
}
}
else {
cout << "Please enter: 1 for X, 2 for O, and 0 if you want you skip the cell";
}
cin >> board_pos;
}
NOTE: The Program does compile!
You are recursively calling main()
.
The standard states :
3.6.1.3
"The function main shall not be used within a program."
5.2.2.9
"Recursive calls are permitted, except to the function named main"
And you are reading the user input after this recursive call to main()
, which, if this call ever succeed, will let no chance to your user to enter anything.
A program that compiles is not necessarily in good program.