Redirected
in Programming in C
1,025 views
3 votes
3 votes
Difference between return 0, return 1, return -1, exit in C?
in Programming in C
by
1.0k views

4 Comments

Aren't they used to take care of exceptions ? Do these statement affect the execution / meaning of the program ?
0
0
how in different cases?
0
0
@srestha , that was a question ! Not an argument :D All I knew about return statement parameter was that :)
0
0

2 Answers

6 votes
6 votes
Best answer

Before this question even I thought these statements were true.

Specific to C as it doesn't support throwing exceptions programmers used the return as a way for your routine to send some information to the parent routine that called it which is considered to be an exit status.

There was something of a convention that 0 meant success, a positive number meant minor problems, and a negative number meant some sort of failure.

Actuallly, after digging into a lot of manuals and C documentation I found this : (here's the link, look at line 54 and 55)

In stdlib.h the macros EXIT_SUCCESS and EXIT_FAILURE are defined like this :

#define EXIT_SUCCESS 0 
#define EXIT_FAILURE 1


These 2 macros can be used as the argument to the exit function declared in stdlib.h and they can also be used as the return value of the main function.

Thank you for the question.

sudoankit.

edited by

4 Comments

edited by

There's the exit() function for that. Check the man page for detailed documentation.

0
0
edited by

Actually I came across something like 

" If return '0'  implies immediate exit from a function "
retunr 1 is normal execution .

Does this affect execution of a code ?

@sudoankit  pls see this too

0
0
edited by

If you look at this code [this one] it returns 1 which is another way of using booleans in C as it doesn't support them. ( Pre C99 ).

You could have returned any postive number in that IsPrime() function and it would have worked fine. If you did pass 0, it would have returned a boolean like false.

Remember return statatements in the main versus the returns in user defined functions work a bit different as you can simulate bool use in C, through them.

0
0
2 votes
2 votes
exit() funtion is a system call which terminate whole program while return statement will terminate only function .

if we use exit(0); or return 0; in main function then effect will be same.

return 1 or return -1 simply returning values 1 and -1 respectively.

Related questions