Home > front end >  How to write an input handling function without global variables?
How to write an input handling function without global variables?

Time:12-25

I want to write a function that will filter the input of the user and then give the filtered string back to the function that had called it.

Is this possible without creating an global variable as in my example?

#include <stdio.h>

char input[10]; //global variable is meh!
char* input_function() {
    
    scanf("%s", input);
    return input;
}

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

CodePudding user response:

Create a character pointer in the main() function and then pass it as an argument to input_function().

#include <stdio.h>
 
char* input_function(char* input) {
    scanf("%s", input);
    return input;
}
    
int main(void)
{
    char input[10];  // Need to allocate space
    printf("%s", input_function(input));
}

CodePudding user response:

Is this possible without creating an global variable as in my example?

As the other answer shows, yes, of course it is possible.

However, be careful about applying a blanket meh to global variables, which have their place.

Also be mindful that C allows module-scope, meaning it is accessible within the module, but not externally. These should not be dismissed.

So it is perfectly acceptable to do:

#include <stdio.h>

static char input[10]; //module scope is OK
static char* input_function() {
    
    scanf("%s", input);
    return input;
}

int main(void) {
    printf("%s", input_function());
}
  •  Tags:  
  • c
  • Related