SiteBanner

So far we've only discussed 'main()' as a block of code that RETURNS a value.  'main()' is the singularly special function all 'C' programs must have one of.  Just as functions can utilize all variety of arguments, functions can return all sorts of values - even returning a structure. 

 

  Typically, the life-span of a variable within a function is limited to the duration that function is used. Using "static char return_string[]" specifies that variable persists after it is first allocated & used.


 

(right-click to download)

/* pgm12 source */

#include <stdio.h>
#include <stdlib.h>   // so the compiler understands 'rand()' & 'srand()'
#include <time.h>    // for any "time-related" functions

char *show_time_now(void);
int     get_random_number(int);

int main(void) {
printf("\n");
printf("Function 'get_random_number()' returned:\n\t%d\n", get_random_number(200));

printf("\n");
printf("Function 'show_time_now()' returned:\n\t%s\n", show_time_now());

return(0);
}

int get_random_number(int modulo_val) {
     // use current time as seed for random generator
     // remove this commented-out line after a few test-runs
     // srand(time(NULL));

     return(rand() % modulo_val); // 'constrain' a larger number to 'modulo_val' or lower
     }

char *show_time_now() {
     static char return_string[35];
     time_t timeval;         // a particular variable type required by function 'time()'

     timeval = time(NULL); // 'time()' specifically needs a 'NULL' argument

     sprintf(return_string, "Current time: %s", asctime(gmtime(&timeval)));   // this line explained in article

     return(return_string);
     }