openlang

Can an input function avoid relying on global variables?

I'd like a function to process what a user enters, filter it, and return the resulting string to whichever function called it.

Can this work without declaring an global variable like the one below?

#include <stdio.h>

char entry[12]; // globals aren't appealing!
char *read_entry() {
    scanf("%s",entry);
    return entry;
}

int main(void) {
    printf("%s",read_entry());
}

The conversation continues 2

Follow the reasoning
  1. Permalink

    Declare a character pointer inside main(), then supply that pointer as a parameter of read_entry().

    #include <stdio.h>
    
    char *read_entry(char *entry) {
        scanf("%s",entry);
        return entry;
    }
    
    int main(void) {
        char entry[12]; // Storage must be reserved
        printf("%s",read_entry(entry));
    }
  2. Permalink

    Can this work without declaring an global variable like the one below?

    Yes, certainly, as demonstrated by the other response.

    Still, don't dismiss every global variable as unappealing, because they do have uses.

    Remember also that C supports module scope, where something can be accessed inside its module but isn't exposed outside it. Those variables deserve consideration too.

    This, therefore, is entirely reasonable:

    #include <stdio.h>
    
    static char entry[12]; // Module scope is fine
    static char *read_entry() {
        scanf("%s",entry);
        return entry;
    }
    
    int main(void) {
        printf("%s",read_entry());
    }

Other sides of the same question

  1. Same sink call, a copy on one line and a move on the next

    Nim 2 decides copy or move per call site. Not per proc. Same argument, same proc. The first call copies, because a is still n…

    Replies 2Latest activity nim
  2. Delaying a cleanup block's mutable borrow until it actually runs

    What would be a way for me to write a panic-safe mecanism in Rust that behaves similarly to Java's try { ... } finally { ...…

    Replies 2Latest activity rust
  3. Inputting character arrays through pointers

    Whenever I attempt keyboard input into some char arrays, my program ends up crashing. What's a straightforward way of reading…

    Replies 2Latest activity c