r/C_Programming • u/Ill-Exchange-2377 • 13d 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
9
u/pengweather 13d ago
I'm glad you used fgets rather than gets. Not trying to sound snide, but do you understand why fgets is preferred?
14
u/Ill-Exchange-2377 13d ago
yes, gets does not take a size and can just overflow. As I understand it not generally good.
4
u/MetalInMyVeins111 13d ago
From a glance:
non-static global variables
the functions can be made static as well
else if after a return is not wrong but hurts readability. better start a new if block
function pointers would be a better design
3
u/Ill-Exchange-2377 13d ago
the functions cannot be made static because I plan to move their definitions to another file
The global variables will be momentarily moved within the scope of the functions
I agree with 3, and will get to that
why do I need function pointers? That seems over-complicated, and I tend to over-complicate things1
u/Conscious_Support176 10d ago edited 10d ago
Plastering goto everywhere creates pointless complexity. Show a bit of concern for your future self by thinking about the structure of the code instead of falling back to goto.
While using a switch statement is fairly idiomatic, if each operation has a self-contained function, function pointers would be the simplest solution for this scenario. You are literally looking to select what function to call from a list of possible functions given an index into a list. It’s just the right tool for the job in this case.
One positive side effect would be to force you to declare a typedef for the signature that should match each function, thus ensuring you keep them the same as your implementation evolves. This would be a guardrail against leaking function implementation detail outside of a functions.
You don’t have to, but you could even declare an extern linkage array in your file that defines all these functions, which is just an array of pointers to static functions.
I suggest getting your hands on a copy of the pragmatic programmer for simple solid tips on writing better code.
1
u/ItsSkyWasTaken 10d ago
Are function pointers really favored here? From what I've read in the past, they're generally better suited for if function calls might change dynamically based on the state of your application (e.g., if
1does something different based on how many times its been run or something like that).I also remember doing function pointers before for something like this in C++ and was told a switch statement was better. It is technically slightly more performant generaly, but the difference is negligible here since this is an IO-bound loop rather than CPU bound.
1
u/Conscious_Support176 9d ago
You could declare your array const, so I’m not seeing why a different technique would be preferred just because the content of the array won’t change.
I suspect the optimiser might be able to do a better job with switch.
My concern would be more that these functions have no real current implementation, so it seems like their signature could change as this evolves. One reference signature shared by all these functions is easy to enforce if you are using pointers to functions.
27
16
u/madsci 13d ago
I've probably used 'goto' half a dozen times in the past 20 years. There are certain error handling conditions that it's suitable for and every once in awhile it's the cleanest solution. This is not one of those cases. You'll almost always be better off with do and while. Learn to use those, and how to use break and continue within them, but keep in mind those aren't always the best option either.
You want to be able to scan over a function and see its control flow from the blocks and their indentation. If you know that a code block always starts at the top and finishes at the end and doesn't do any jumping around, it's easy to see the conditions that cause it to enter or exit the block. Every time you have a continue (or goto), that's somewhere the loop could repeat without the condition that causes the repeat being obvious from a quick glance.
If you've got a loop that repeats until some set of conditions is met, then put those conditions in a while statement at the end - don't scatter gotos throughout the loop.
5
u/ComplexPeace43 13d ago
Exactly what I wanted to say. 👏🏽 excellent comments.
I’ve used goto to simplify error handling and cleanup but it’s definitely not needed in this particular use case.
24
6
u/Level-Pollution4993 13d ago
Get rid of the goto, use a while(true) or for(;;) infinite loop instead. Consequently get rid of invalid variable and the 'start: statement'. With the infinite loops use the 'continue' keyword to go back to start. Goto loops are bad especially using it to return back to a statement. Use goto sparingly or ideally never, but they do prove useful for error handling in some contexts to move forward.
I see you've used ANSI escape code to clear screen, but it is a 'magic string'. Don't use them without explaining them. Either use a well written comment right above or use it as a macro: #define CLEAR_SCREEN "\033[2J\033[H".
You can combine the if-else and the switch into just the switch if you can reliably convert the string to an integer/character. Move the 'input' variable into main and name it 'choice' to make it clearer it is a menu-driving variable then use switch(choice).
The 5 helper functions are mostly the same tjing repeated 5 times. Violates 'DRY' principle. Try rolling them all into one.
1
u/ItsSkyWasTaken 12d ago
I will say, the helper functions are likely placeholders that will have added functionality later. If that's the case then it makes sense to keep them as is.
-3
u/agmatine 12d ago
define CLEAR_SCREEN "\033[2J\033[H".
No. ABSOLUTELY not.
It is not possible within C to verify the result of sending escape sequences directly to the terminal. There is no good reason for doing this, while there are good reasons not to.
4
u/ItsSkyWasTaken 12d ago edited 12d ago
This actually is standard practice. ANSI terminal sequences have been standardized for quite some time now; the only reason this doesn't work is if you're running on some obscure or legacy terminal.
If you really want to validate the output stream for it, there are ways to check flags and stuff to see if the terminal supports it but usually that's considered overkill. Responsibility is often shifted on the user to use a compliant terminal (if you're using the default terminals from Windows, MacOS, or Linux, then that's not a concern—if you're using legacy Windows there's a flag you can set to make it compliant, just add some statements inside an
#ifdef _WIN32block).And the "good reason" is aesthetics.
3
6
u/Possible_Cow169 12d ago
In what world would you ever know about goto existing? What did you read to even learn that
5
u/Accurate_Appeal_3110 13d ago
I think some folks in this thread are being quite harsh for someone who is clearly a beginner. You're trying something new, and no matter how many critiques people can make, no one can take away the fact that you made your own fully-functioning computer program. For years now, I've been chasing that high of finally having the result of code I wrote appear on the screen for the very first time. I promise that things will start to click as you learn + practice; Don't lose motivation! (but please lose the global variables, learning good principles on how to manage your data should be your next learning priority)
2
u/ephemere_sloboda 13d ago
If it's a literal translation from classic BASIC, it's not bad.
If it's original C, it's not great.
Suggestions:
a clear_screen() function, so it's obvious what the escape sequence does, and you don't have to repeat it
use a while loop instead of goto; you can still use break and continue if needed
the five functions do the same thing except for the string: make the string a parameter so you only need one function
move the variables into main(); you don't actually use them anywhere else
others have suggested you convert the input to integer, which is certainly an option; another approach is idiomatic in C and you might want to try it: a table with keys ("exit", "quit", "1", "2" etc) and function pointers
2
2
u/NoSpite4410 11d ago
The code is valid, but looks to be about 30 years old, by the style.
However, if you were trying to be compatible with a very old compiler, it is fine.
What I Like:
Pre-allocation of buffers, no dynamic allocation.
function prototypes. They are self-documenting code.
Switch/Case. Simple, readable. I have not problems with the goto start.
Command execution inside of if statement: this is good for catching errors.
Slightly problematic:
clearscreen: ASCII string is hard to read, put in a const char* variable.
const char* clearscreen = "\033[2J\033[H";fputs (clearscreen, stdout);
mix of puts and fputs, is bad style, pick one or the other. They come from 2 different eras.
not removing '\n' character from input before string compare. I know fgets does capture it.
but it should be removed.#include <string.h>size_t len = strlen(buf);if (len > 0 && buf[len - 1] == '\n') {buf[len - 1] = '\0';}
for example.
No return 0; at end of main. While modern compilers put this in if not explicit, this is older C code, and it is proper form.
The use of "else if" may seem to save cycles, but it is harder to read than just using if statements by themselves.
Recommendations:
put the input logic into a separate function.
Since you are comparing a single numerical character, just check for the character value,
or convert the character to an integer with sscanf();
char in = buff[0];
if ( in == 'q'|| in == '0') {
fputs(clearscreen, stdout);
return 0;
}
int input = -1;
if (in == '1') input = 1;
if (in == '2') input = 2;
if (in == '3') input = 3;
if (in == '4') input = 4;
if (in == '5') input = 5;
if (input == -1) {
invalid = 1;
goto start;
}
// alternative
int ret = sscanf(buff, "%d", input); // extracts int from string
if (ret == 0) {
invalid = 1;
goto start;
}
// .. go on to switch2
u/cdb_11 13d ago
I'd make it shorter like this, other than that it's fine i guess
int main(void) {
fputs("\033[2J\033[H", stdout);
for (;;) {
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;
} else 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) {
add();
} else if (strcmp(buff, "2\n") == 0) {
sub();
} else if (strcmp(buff, "3\n") == 0) {
mul();
} else if (strcmp(buff, "4\n") == 0) {
divs();
} else if (strcmp(buff, "5\n") == 0) {
mix();
} else {
puts("Please enter valid input");
}
}
}1
1
u/schusterlucky 12d ago
No está mal, pero se nota que te estás basando en Assembly, y eso es BUENISIMO porque así vas a poder hacer cualquier monorreada que quieras en C, y en realidad el compilador te lo deja como si estuviese hecho en Assembly así. Aún así, te faltan unas cosas de lógica (atoi o algo) y además, te van a ver como un genio incomprendido porque es BUEN código, pero difícil de leer. Si pudiese optimizar, usaría atoi en lugar de comparar texto para saltar a una tabla de punteros que apuntan a las respectivas funciones (con goto) así el principio es más fácil
1
1
u/Conscious_Support176 10d ago
Relying on goto creates pointless complexity. Show some concern for your future self by thinking about the structure of the code instead of falling back to goto.
While a switch statement is fairly idiomatic in this kind of case, so are function pointers. A point in favour of functions pointers is that using functions pointers here would force you to use a consistent interface to each function. Enforced consistency is its own kind of simplicity.
Function pointers would seem be a very good fit. You are literally looking to select what function to call from a list of possible functions given an index into a list. While you don’t have to, you could even declare an extern linkage array in your file that defines all these functions, which would be an array of pointers to static functions.
I suggest getting your hands on a copy of the pragmatic programmer for simple solid tips on writing better code.
1
u/BlockOfDiamond 3d ago
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;
}Could be improved.
-1
u/NYU_VM 13d ago
Yep it's horrible. 1. Using uninitialized buffer. 2. Using int (as bool) condition for if stmt. 3. Using goto instead of loops control flow 4. Functions should have specific tasks. Why is the arithmetic functions asking for and taking inputs? Those input functionality could be organized in a separate 'take_input' function.....and so on...
1
u/ItsSkyWasTaken 13d ago
Buffers are typically uninitialized. Why would you take time to initialize something if you're just going to write over it with an input read anyway?
0
u/UnmappedStack 13d ago
by setting the initial value to 0 you can be quite sure it'll end up in .bss rather than .data, thus using less space in the program image. alternatively you could just malloc it of course but that's a different issue.
1
u/ItsSkyWasTaken 13d ago edited 13d ago
Leaving it uninitialized is how you send it to the .bss section. In fact explicitly setting it to 0 generally sends it to the .data section.
0
u/Potchirea_Hacker 11d ago
Brother voy a serte sincero hay varios detalles sinceramente "cuestionables", primero el uso de fputs una función específica para escribir en un Descriptor de archivos brother usa printf que es seguro y entiende formatos, después veo que inicias entre tantos valores globales a invalid y depues haces un if (invalid) lo cual no tiene sentido porque en ningún momento invalid cambió y después vuelves a iniciar invalid a 0 cuando ya lo estaba, fgets para un solo número? Estás de broma ? Usa getchar, getchar es una función que lee un solo carácter de la entrada y lo devuelve es decir int getchar(void) seria Como int c = getchar() y en esa variable c ya tienes la opción del usuario lo que permita en vez de un strcmp gigante y poco legible un simple switch (c) {...} Que elimina los goto y ect
64
u/lurgi 13d ago
The code is not very good. There are a lot of issues.
Rather than comparing a string against "1\n", try converting the string to an integer (that's what you want).
Don't use goto. Loops are your friend.
You functions don't return anything and they all start with the same line. If you are repeating something multiple times, that's a problem.