Exiting a program using exit() function


$ls
ascii-table     avg.txt               case-changer.c  env-var-set    functions_ver1    mph-to-kph.c
ascii-table.c   avg-with-garbage.txt  env-var         env-var-set.c  functions_ver1.c  mph-to-kph_v2.c
ascii-table.md  case-changer          env-var.c       exist.sh       functions_ver2.c  output.c
$zile functions_ver2.c 
$gcc functions_ver2.c -o functions_ver2
$./functions_ver2
Inside main
Calling function one
Inside function one
Calling function two
Inside function two
Returning with (error) from function two
$cat functions_ver2.c
#include <stdio.h>
#include <stdlib.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 funtcion 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");
      exit(0);
   }
   else
   {
      printf("Caught an error from function two\n");
      exit(1);
   }
}

int func2(void)
{
   printf("Inside function two\n");
   printf("Returning with (error) from " 
      "function two\n");
   exit(1);
}
$

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: