-
Beginner help
I am trying to have my switch case statements print with defined functions but they are not working. I have defined the statements, but it seems that the error is in the function itself.
Code:
#include <stdio.h>
#include <stdlib.h>
nstructions() {printf("\nHere are the instructions:"), printf("You may have myself or the computer give you a number.\n")};
user_guess(){printf("The number the computer is thinking of is...10.\n")};
computer_guess(){printf("\nThe number I'm thinking if is...5")};
main(void)
{
int menu_choice;
printf("\tGUESSING GAME /n");
//Menu list of choices
printf("1. Show me the instructions\n");
printf("2. Let the computer think of a number\n");
printf("3. I will think of a number\n");
printf("0. Quit\n");
do
{
printf("Enter your choice: ");
scanf(" %d", &menu_choice);
switch (menu_choice)
{
case (1): instructions();
break;
case (2): user_guess();
break;
case (3): computer_guess();
break;
case (4): exit(1); //Exits the program.
break;
//Validates input
default: printf("\n%d is not a valid choice.\n", menu_choice);
printf("Try again.\n");
break;
}
} while ((menu_choice < 1) || (menu_choice > 4));
return 0;
}
-
1. Make all your functions return a proper type.
2. There's no benefit to writing code all on one line.
3. There's no benefit in abusing the comma operator.
4. There's no need for a trailing ; at the end of the function.
4. Your statements inside the function DO however need ;
Code:
void instructions() {
printf("\nHere are the instructions:");
printf("You may have myself or the computer give you a number.\n");
}
-
Thanks. That was clearest response from the three forums I have tried. My book did not make it clear that your function needs to be inside of curly braces.
-
The 'all on one line with a ';' on the end' thing might be stylistically influenced by C++, where it is often used for small functions in class definitions.
But it is not the done thing for plain C.