Search code examples
crecursiongccreturnwindows-subsystem-for-linux

Returns without a "return" command


C programming language, compiled with gcc, terminal bash in WSL

I have written a recursive function, to find the lowest number in an array, which works just fine.

/*01*/    int minimo(int array[], int n)
/*02*/    {
/*03*/      static int min = 0;
/*04*/    
/*05*/      if (n == N)
/*06*/      {
/*07*/          return array[n-1];
/*08*/      }
/*09*/      else
/*10*/      {
/*11*/          min = minimo(array, n+1);
/*12*/          if(array[n]<min){
/*13*/              min = array[n];
/*14*/          }
/*15*/      }
/*16*/    }

The only problem is that it shouldn't work, because it doesn't return "min" to the caller...

int main()
{
    //Var
    int array[N] = {10, 2, 5, 1, 7};
    printf("Min: %d\n", minimo(array, 0));
}

My concern is actually a problem, but not on my machine onto which the function works just fine as it is; it is a problem on my friends' laptops and IDEs, I tried copying to XCode on a friend's Macbook and it wouldn't work if the line "return min;" wasn't added at the end of the function.

Between line 15-16 I have to add return min;

/*15*/      }
            return min;
/*16*/    }

My questions for you are the following:

  1. How can a function return a variable automatically?
  2. Is it possible that it does return the only variable that I created (static int min)?
  3. Or is it a "problem" related to the static attribute that the variable has?
  4. Does it have anything to do with the nature of the function (recursive)?

This is my first post, please be kind if I'm breaking any forum rule.


Solution

  • My concern is actually a problem, but not on my machine onto which the function works just fine as it is; it is a problem on my friends' laptops and IDEs, I tried copying to XCode on a friend's Macbook and it wouldn't work if the line "return min;" wasn't added at the end of the function.

    Typical example of undefined behavior. Works on one machine but not another. Works at daytime but not nighttime. Works with one compiler but not another. When you invoke undefined behavior, the C standard imposes no requirements on how the code should behave.

    C11 standard 6.9.1.12

    If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

    In your code, that is precisely what happens. You invoke undefined behavior when you try to print the return value.

    Contrary to what many believes, it IS completely allowed to omit the return statement in a non-void function. It only becomes undefined behavior if you try to use the non-existent return value.

    To avoid this, always compile with at least -Wall -Wextra.