Exiting a program with relevant return value


$ls
ascii-table     avg.txt               case-changer.c  env-var-set    functions_ver1.c  mph-to-kph_v2.c
ascii-table.c   avg-with-garbage.txt  env-var         env-var-set.c  functions_ver2.c  output.c
ascii-table.md  case-changer          env-var.c       exist.sh       mph-to-kph.c
$cat functions_ver1.c
#include <stdio.h>
int func1(void);
int func2(void);

int main(int argc, char *argv[])
{
   printf("Inside main\n");
   printf("Calling function one\n");
   if (func1())
   {
      printf("Everything ok from function one\n");
      printf("Return with 0 from main - all ok\n");
      return 0;
   }
   else
   {
      printf("Caught an error from function one\n");
      printf("Return with 1 from main - error\n");
      return 1;
   }
   return 0; /* We shouldn't reach this, but 
                just in case */
}

int func1(void)
{
   printf("Inside function one\n");
   printf("Calling function two\n");
   if (func2())
   {
      printf("Everything ok from function two\n");
      return 1;
   }
   else
   {
      printf("Caught an error from function two\n");
      return 0;
   }
}

int func2(void)
{
   printf("Inside function two\n");
   printf("Returning with 0 (error) from "
      "function two\n");
   return 0;
}
$gcc functions_ver1.c -o functions_ver1.c 
gcc: fatal error: input file ‘functions_ver1.c’ is the same as output file
compilation terminated.
$gcc functions_ver1.c -o functions_ver1
$./functions_ver1 
Inside main
Calling function one
Inside function one
Calling function two
Inside function two
Returning with 0 (error) from function two
Caught an error from function two
Caught an error from function one
Return with 1 from main - error
$

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: