So what does “return 0” actually mean?

后端 未结 6 594
谎友^
谎友^ 2020-12-08 12:02

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

相关标签:
6条回答
  • 2020-12-08 12:19

    The C programming language allows programs exiting or returning from the main function to signal success or failure by returning an integer, or returning the macros EXIT_SUCCESS and EXIT_FAILURE. On Unix these are equal to 0 and 1 respectively. A C program may also use the exit() function specifying the integer status or exit macro as the first parameter.

    Apart from the macros EXIT_SUCCESS and EXIT_FAILURE, the C standard does not define the meaning of return codes. Rules for the use of return codes vary on different platforms.

    0 讨论(0)
  • 2020-12-08 12:24

    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.

    0 讨论(0)
  • 2020-12-08 12:33

    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.

    0 讨论(0)
  • 2020-12-08 12:37

    Functions in C return int by default, if no other return type is defined. return 0 would be good practice to make sure the function returns a known value, as opposed to some random value, in case the caller is looking at the return value.

    0 讨论(0)
  • 2020-12-08 12:37

    It is literally returning an int of 0.

    0 讨论(0)
  • 2020-12-08 12:38

    In C you don't have to return a value only if you declare a function with void at the start of it. First example:

    #include <stdio.h>
     int main()
    {
       printf("Hello World!");
        return 0; // you have to use return because main starting with int
    }
    

    Second Example:

    #include <stdio.h>
    void main()
    {
    printf("Hello World!");
    //in this case return is useless, main is a void function
    
    }
    
    0 讨论(0)
提交回复
热议问题