Search code examples
cfunctionreturnreturn-value

Can a function be defined after main()?


I have a code which looks like this and executes completely fine,

#include <stdio.h>

int main( )
{
int i = 3, j = 4, k, l ;
k = addmult ( i, j ) ;
l = addmult ( i, j ) ;
printf ( "\n%d %d", k, l ) ;
}
int addmult ( int ii, int jj )
{
int kk, ll ;
kk = ii + jj ;
ll = ii * jj ;
return ( kk, ll ) ;
}

My question is that can we define a function afterwards without defining function prototype at the top and how can a function return two values?


Solution

  • can we define a function afterwards without defining function prototype at the top

    You can declare its proto in main. In your case, the function accepts ints and returns an int, so the default prototype (are they still alive in the Standard?) worked fine.

    how can a function return two values?

    1. It can return a struct by-value:

      typedef struct { int first; int second; } int_pair;
      int_pair addmult(int x, int y) {
          return (int_pair){42, 314}; /* enough for the demo, lol (c) */
      }
      

      Or by-pointer:

      int_pair *addmult(int x, int y) {
          int_pair *retVal = malloc(sizeof(int_pair));
          return retVal->first = 42, retVal->second = 314, retVal;
      }
      int_pair *multadd(int x, int y) {
          static int_pair retVal{314, 42};
          return &retVal;
      }
      
    2. It can return a fresh array on the heap:

      /* 1. It is user's responsibility to free the returned pointer. */
      int *addmult(int x, int y) {
          int *retVal = malloc(2 * sizeof(int));
          return retVal[0] = 42, retVal[1] = 314, retVal;
      }
      
    3. Finally, it can return an array without allocating the latter on heap:

      /* 1. It is user's responsibility to NEVER free the returned pointer. */
      int *addmult(int x, int y) {
          static int retVal[] = {42, 314};
          return retVal;
      }
      

      In this case, the returned array can be reused (rewritten) by consequent calls so you should make use of its contents as soon as possible.