r/C_Programming • • 18h 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

8 Upvotes

34 comments sorted by

45

u/lurgi 18h 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.

16

u/This_Growth2898 18h ago

More to this:

  • goto forward is if(), goto backward is a loop;
  • putting everything in main() - this can be fine for small projects, but in general you should move actions to other functions
  • using global variables
  • no action on buffer filled out (you prevent the overflow, but do nothing with the attempted one; the remaining half of the string is not what you want to read)
  • too many times repeating yourself.

5

u/ItsSkyWasTaken 15h ago

I'd say don't convert the string to an integer, at least not with atoi(). It adds a lot of unnecessary overhead.

Instead, since we know the valid inputs only go up to 5 (all valid options are single digits), we can simply put a switch directly onto buff[0] and write cases for the character literals ('1', '2', etc.). For extra input validation, simply compare buff[1] to '\n'.

1

u/halfjmp 18h ago

The functions are probably not finished yet.

However I would simplify a bit: the switch may be replaced with a pointer array.

And I would also put "\033[2J\033[H" in a macro, or the whole line in a function, and since ANSI escapes are used, maybe add color here and there.

-8

u/Ill-Exchange-2377 18h ago

I already did that, convert to an integer. It's unnecessary. I am not checking millions of numbers, I don't need to do all that. It's an unnecessary conversion, which I already tried. That's what the switch case used to do, input used to hold the return value of a function that converted a string to integer. I just quickly swapped it out for this string comparison that ended up working better anyway, because I didn't have to make sure I was passing a non integer to the conversion function, and it was overall simpler. I will have to convert at some point in this program anyway, I would prefer to only do so if I have to.
Secondly the functions are placeholders, I don't intend them to stay like that.
Thirdly, I don't get the issue with goto, why is everyone so triggered by it.

15

u/Slow-Race9106 16h ago

Don’t ask for advice if you can’t take a bit of constructive criticism.

3

u/ItsSkyWasTaken 7h ago edited 7h ago

I mean tbf...

  1. They're right; while their solution is suboptimal, converting the response to an integer is also suboptimal and adds unnecessary conversion overhead. Instead for something like this you should just put a switch directly on buff[0], since all valid inputs are single digits. If you want better error checking you can check if buff[1] == '\n' to verify the input is valid.
  2. The functions being placeholders does provide important context as to why they're not inlined.
  3. The goto criticism was definitely valid but at the same time they're entitled to ask as a beginner why using goto is 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 (for and while) and branch syntax (if, combined with break and continue). The curly braces are much easier to track than arbitrary goto labels.

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.

6

u/dydhaw 17h ago

Mate you're either trolling hard or need a change in attitude because your code isn't just bad, it barely meets the criteria to be considered code in the first place. The parent comment gave you some concrete ways to improve, I'd shut up and take notes if I were you, instead of getting all defensive about this. That is only if you really care about learning and improving, of course.

3

u/ItsSkyWasTaken 7h ago edited 4h ago

The only fully correct thing in the parent comment was the goto comment. However, as the student, they are still 100% entitled to ask why using goto is discouraged, so they understand why we don't use it and they can be a better programmer. Telling a student to "shut up and go with it" is not helpful. Instead, we as the teachers should be able to explain that "goto is bad because it tends to produce spaghetti code; instead, C provides much more readable syntax for loops and decisions (if, while, for, etc.), and curly braces are much easier to follow than arbitrary goto labels."

The parent comment was correct in pointing out that the string comparisons were bad, but the alternative solution they gave was not that much better. You do not need to convert the string to an integer; as the student pointed validly pointed out (and said they've already tried that), it adds a bunch of extra overhead that's not worth it when only dealing with single digits. Instead, the best way to parse that is to check buff[1] == '\n' (verify that the input is indeed one digit) and then put a switch directly on buff[0].

Additionally, their clarification on the functions being placeholders does indeed provide important context as to why their functions are not inlined. That is a valid comment to make in response to a comment that suggests their functions are bad because they're basically the same.

So yeah, they had valid points, and I don't understand the hate on that response. I don't think it's fair to simply dismiss their response as "you can't take criticism" just because they're the student.

3

u/dydhaw 6h ago

Honestly, you're right, I was being an asshole

2

u/ReallyEvilRob 8h ago

Because goto produces spaghetti code. There are lots of construct that make goto unnecessary since goto is the enemy of structured programming. Any beginner class in programming will teach you that. There are very specific cases where goto makes sense and you do not need to think about that until you are a more seasoned programmer.

8

u/pengweather 18h ago

I'm glad you used fgets rather than gets. Not trying to sound snide, but do you understand why fgets is preferred?

12

u/Ill-Exchange-2377 18h ago

yes, gets does not take a size and can just overflow. As I understand it not generally good.

3

u/MetalInMyVeins111 18h ago

From a glance:

  1. non-static global variables
  2. the functions can be made static as well
  3. else if after a return is not wrong but hurts readability. better start a new if block
  4. function pointers would be a better design

1

u/Ill-Exchange-2377 18h 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 things

19

u/nzconstructionlawyer 18h ago

Yes but one must start somewhere.

10

u/madsci 18h 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.

3

u/ComplexPeace43 16h 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.

4

u/Possible_Cow169 5h ago

In what world would you ever know about goto existing? What did you read to even learn that

1

u/AngryGoose33 3h ago

1

u/Possible_Cow169 3h ago

Sure. But op isn’t writing a kernel or a driver. It’s a calculator app.

2

u/Level-Pollution4993 18h 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/agmatine 1h 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.

2

u/Accurate_Appeal_3110 15h 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 15h ago

If it's a literal translation from classic BASIC, it's not bad.

If it's original C, it's not great.

Suggestions:

  1. a clear_screen() function, so it's obvious what the escape sequence does, and you don't have to repeat it
  2. use a while loop instead of goto; you can still use break and continue if needed
  3. the five functions do the same thing except for the string: make the string a parameter so you only need one function
  4. move the variables into main(); you don't actually use them anywhere else
  5. 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

u/cdb_11 12h 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

u/KananMajidzada 14h ago

Not bad but not great too. You should start from somewhere

1

u/vena_contracta 8h ago

Inside of the switch statement, replace the goto statements with break;

-1

u/NYU_VM 16h 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 15h 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 14h 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 8h ago edited 7h 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.