r/C_Programming • u/Ill-Exchange-2377 • 11d ago
Is my code bad?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char buff[100];
void add(void);
void sub(void);
void mul(void);
void divs(void);
void mix(void);
int invalid = 0;
int input = 0;
int main(void) {
start:
fputs("\033[2J\033[H", stdout);
if (invalid) {
puts("Please enter valid input");
}
invalid = 0;
puts("Pick a subject:");
puts("1: Addition");
puts("2: Subtraction");
puts("3: Multiplication");
puts("4: Division");
puts("5: Mixed");
puts("Pick a number 1-5, or use 'quit' or 'exit' to leave the program");
if (fgets(buff, sizeof(buff), stdin) == NULL) {
puts("Failed, exiting");
return 1;
}
if (strcmp(buff, "quit\n") == 0 || strcmp(buff, "exit\n") == 0) {
fputs("\033[2J\033[H", stdout);
return 0;
} else if (strcmp(buff, "1\n") == 0) {
input = 1;
} else if (strcmp(buff, "2\n") == 0) {
input = 2;
} else if (strcmp(buff, "3\n") == 0) {
input = 3;
} else if (strcmp(buff, "4\n") == 0) {
input = 4;
} else if (strcmp(buff, "5\n") == 0) {
input = 5;
} else {
invalid = 1;
goto start;
}
switch(input) {
case 1:
add();
goto start;
case 2:
sub();
goto start;
case 3:
mul();
goto start;
case 4:
divs();
goto start;
case 5:
mix();
goto start;
default:
goto start;
}
}
void add(void) {
puts("add");
fgets(buff, sizeof(buff), stdin);
}
void sub(void) {
puts("sub");
fgets(buff, sizeof(buff), stdin);
}
void mul(void) {
puts("mul");
fgets(buff, sizeof(buff), stdin);
}
void divs(void) {
puts("divs");
fgets(buff, sizeof(buff), stdin);
}
void mix(void) {
puts("mix");
fgets(buff, sizeof(buff), stdin);
}Is my code that bad?
For context this is a project I was doing to learn the C
Edit: Fixed formatting errors
23
Upvotes
View all comments
Show parent comment
8
u/ItsSkyWasTaken 11d ago edited 11d ago
I mean tbf...
buff[0], since all valid inputs are single digits. If you want better error checking you can check ifbuff[1] == '\n'to verify the input is valid.gotocriticism was definitely valid but at the same time they're entitled to ask as a beginner why usinggotois bad. The answer we could've given them is that it tends to create spaghetti code, and C offers much more readable constructs like dedicated loop syntax (forandwhile) and branch syntax (if, combined withbreakandcontinue). The curly braces are much easier to track than arbitrarygotolabels.I don't exactly understand why their response got so much hate. The response had some valid points, and it seems unfair to just dismiss them as "you can't take criticism" just because they're the student.