How to Quit One Program and Run Another in C Programming

By Dan Gookin

In C programming, information can get into your program via command-line arguments. Information gets back out thanks to the return statement. That’s the primary way, but not the only way, a program bails out when it’s done.

How to quit the program

Your program quits when the main() function encounters the return statement. Traditionally, that statement appears at the end of the function, but it doesn’t always need to go there. Further, you can use the exit() function to leave the program at any time, even within a function other than main().

The exit() function is used to gracefully quit a program, tying up any loose ends, tucking variables into bed, and so on. In There Must Be Some Way out of Here, this function is used at Line 17 to leave the program in the sub() function.

THERE MUST BE SOME WAY OUT OF HERE

#include <stdio.h>
#include <stdlib.h>
void sub(void);
int main()
{
 puts("This program quits before it's done.");
 sub();
 puts("Or was that on purpose?");
 return(0);
}
void sub(void)
{
 puts("Which is the plan.");
 exit(0);
}

You need to include the stdlib.h header file to use the exit() function, and it uses an int value as an argument for the exit status, similar to the value passed by return in the main() function.

Exercise 1: Type the source code from There Must Be Some Way out of Here into your edit. Build and run the program.

How to run another program

The system() function directs your program to run another program or to issue a command. For example:

system("blorf");

The preceding statement directs the operating system to issue the blorf command, running whatever program has that name or carrying out whatever actions the blorf command dictates.

After running the command, control returns to your program, which continues with the statement following the system() function.

Clearing Things Up contains two system() functions; your code needs only one. Use the first system() statement if you’re using Windows; use the second statement if you’re using anything else. Or you can just comment out the statement rather than delete it.

CLEARING THINGS UP

#include <stdio.h>
#include <stdlib.h>
int main()
{
 printf("Press Enter to clear the screen:");
 getchar();
 system("cls"); /* Windows only */
 system("clear"); /* Mac - Unix */
 puts("That's better");
 return(0);
}

Line 2 includes the stdlib.h header file, which is required for the system() function to work. Ensure that the command to be run is enclosed in double quotes or is represented by a char array (string).

Exercise 2: Create a new project by using the source code shown in Clearing Things Up. Build and run.