OK, first of all, I am not a programmer. (yes, I heard the “thank god”) Perhaps I could make the top example simpler.

But anyway, I kind of like goto too much. I find it more intuitive to just jump around and re-use parts rather than think about how to do loops without too much nesting.

In high school, we only did Python. I really wanted to do goto in Python as well, but all I found was this April fools’ goto module.

Now in college we’re starting with C, and I am starting with Bad HabitsTM.

Anyway, tagging every line was BASICally just for the joke, but it is useful to just jump to any random line.

  • kryptonianCodeMonkey@lemmy.world
    link
    fedilink
    arrow-up
    6
    ·
    edit-2
    2 hours ago

    But anyway, I kind of like goto too much. I find it more intuitive to just jump around and re-use parts rather than think about how to do loops without too much nesting.

    Might I introduce you to functions?

    Need to write a prompt to the console and get an input? That could be a function. Need to check if a character matches some option(s)? That’s could be a function. Need to run a specific conditional subroutine? That could be a function. And function names, done correctly, are their own documentation too.

    You main function loop could look almost like pseudo code if you do it right.

    #include <stdio.h>
    #include <stdlib.h>
    #include <stdbool.h>
    #include <string.h>
    
    char* prompt_for_input(const char* prompt_message) {
        char temp[100];
        printf(prompt_message);
        fgets(temp, 100, stdin);
        temp[strlen(temp)-1] = '\0';
        char* input = malloc(strlen(temp));
        strcpy(input,temp);
        return input;
    }
    
    int string_to_int(char* input) {
        return (int)strtol(input, NULL, 10);
    }
    
    int prompt_for_loop_count() {
        char *input = prompt_for_input("\nI'll loop over this many times: ");
        int loop_count = string_to_int(input);
        free(input);
        return loop_count;
    }
    
    bool prompt_to_do_again(){
        char *input = prompt_for_input("Let's do that again!\nShallow we? (y/n): ");
        bool do_again = (strcmp(input, "y") == 0 || strcmp(input, "Y") == 0);
        free(input);
        return do_again;
    }
    
    int main() {
        bool need_to_get_loop_count = true;
        while(need_to_get_loop_count) {
            int loops_remaining = prompt_for_loop_count();
            do {
                printf("Current = %d\n", loops_remaining);
                loops_remaining--;
            } while(loops_remaining > 0);
            need_to_get_loop_count = prompt_to_do_again();
        }
    }