Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

So what does "return 0" actually mean?

Tags:

c

return

I'm pretty proficient in PHP, but I've started dabbling with C. I've seen the code

return 0;

at the end of functions that don't return a value. This isn't used in PHP, because if a function is doesn't have a return, a value NULL is automatically returned.

All I'm asking is, in simple English, what does the return 0 actually do? Is it like PHP, where it returns its argument as the value of the function call? Is it just good practice?

I know this question has been asked many times before, but I'm asking it from the point of view of a PHP developer. The answers google throws up haven't been that concise.

like image 999
Starkers Avatar asked Feb 18 '13 02:02

Starkers


People also ask

What is the point of return 0?

return 0 in the main function means that the program executed successfully. return 1 in the main function means that the program does not execute successfully and there is some error. return 0 means that the user-defined function is returning false.

What happens if I dont use return 0?

Short Answer: Nothing. Better Answer: return 0 it's used in main like a signal for know the exit of program was a success when return 0 executes. Best Answer: Still nothing because compilers already "put" return 0 in the the end of your code if you not explicit.

Is returning 0 necessary?

No, its not necessary. Here int is the return type of the main program. The main function returns nothing generally, thus we are writing 'return 0' at the end of it.


2 Answers

Is it like php, where it returns its argument as the value of the function call? Is it just good practise?

Yes, PHP and many other languages borrowed the return keyword from 'C'. And in all the languages, the return keyword has the same function - to return from the function. Anything that follows return keyword is the value that is returned to the caller.

Is it a good practise? Yes and No. Not all functions should return a value. And quite a few in the standard library even, do not return any value. Hence their return type is void.

But main function should return 0(also EXIT_SUCCESS) to identify that the program has executed successfully. And -1 otherwise (also EXIT_FAILURE)

EDIT: (Thanks to @KeithThompson):

EXIT_FAILURE is implementation defined. 1 is a common value of EXIT_FAILURE but the whole point is, you need not know.

like image 116
Aniket Inge Avatar answered Nov 10 '22 07:11

Aniket Inge


For historic reasons, it is possible to write return 0; to return from a function that has been declared as void, like so:

void foo( /* arguments */ )
{
  /* do things */
  return 0;
}

This does nothing, and the 0 (or whatever you put there) is thrown away. Also, sensible compilers will give you a warning message if you do this. So don't do this.

like image 29
Brooks Moses Avatar answered Nov 10 '22 09:11

Brooks Moses