Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using exit(1) to return from a function

Tags:

c++

c

linux gcc 4.4.1 C99

I am just wondering is there any advantage using the following techniques. I noticed with some code I was reading the exit number went up in value, as displayed in this code snippet.

/* This would happen in 1 function */
if(test condition 1)
{
    /* something went wrong */
    exit(1);
}

if(test condition 2)
{
    /* something went wrong with another condition*/
    exit(2);
}

or doing the following and just returning:

/* This would happen in 1 function */
if(test condition 1)
{
    /* something went wrong */
    return;
}

if(test condition 2)
{
    /* something went wrong with another condition*/
    return;
}
like image 214
ant2009 Avatar asked Nov 27 '22 23:11

ant2009


1 Answers

exit() exits your entire program, and reports back the argument you pass it. This allows any programs that are running your program to figure out why it exited incorrectly. (1 could mean failure to connect to a database, 2 could mean unexpected arguments, etc).

Return only returns out of the current function you're in, not the entire program.

like image 149
Tyler Smith Avatar answered Dec 14 '22 09:12

Tyler Smith