Search code examples
cstringreturnreturn-typeboolean-expression

Why can an int return type function return a string?


This is the function I'm talking about:

static int getInput()
{
    printf("Enter your name: ");
    return fgets(input, sizeof(input), stdin) != NULL;
}

How does this work? Why can an int return type use fgets like this?


Solution

  • "Why can an int return type function return a string?"

    In fact, It can´t.

    Let´s take a closer look at this statement:

    return fgets(input, sizeof(input), stdin) != NULL;
    

    fgets() returns a pointer to char. This pointer is checked for a null pointer. The validation of this boolean expression either evaluates to 1 if the returned pointer is a non-null pointer (fgets() actually returned a pointer to input) or 0 if it is a null pointer - means an error occurred at consuming input by the use of fgets().

    This int value (0 or 1) is then returned from the function getInput(); not a pointer or even a string by value itself (which is impossible regarding the C syntax).


    Side notes:

    1. input seems to be a global char array. Avoid global arrays. It can confuse you and readers. Pass a pointer to the buffer by reference and also pass the size of the buffer by value instead.

      static char* getInput (char* buf, size_t len)
      {
          if ( len > INT_MAX || len < 2 )
          {
              return NULL;
          }
      
          printf("Enter your name: ");
          return fgets(buf, len, stdin);
      }
      

      and call it like:

      char a[20];
      if ( getInput(a, sizeof(a)) == NULL )
      {
          fputs("Error occured at consuming input!", stderr);
      }
      
    2. For the meaning of the static qualifer in this example, take a look at:

      What is a "static" function in C?