The difference between C language return 0 and -1

Asked 1 years ago, Updated 1 years ago, 79 views

I was watching a C language lecture and said, "I have to do return -1; to end the program," but isn't return 0; also ending the program? What is the difference between the two returns? If there is no difference, why do you use return -1;?

return c

2022-09-22 19:43

1 Answers

The return value of the main() function is used to inform the OS if the program has shut down successfully.

From Unix, which is the period of Hyundai OS, most modern OSs believe that the program terminated normally if the return value of main() is 0, or an error occurs. A value other than 0 is an error code, which is also a criterion for determining what error has occurred.

Therefore, whatever the return value of main() is, the program ends. As you said, returning -1 will inform the OS that an error has occurred and it has been terminated.

To end the program, you have to return -1;. Since there is no contextual content before or after the program, it is not clear what it means, but let's assume that it means that the program has an error and should be terminated.

The value -1 indicates the failure of the API call in Unix-like system calls. Further information about the failure is provided through errno.

int ret = write(fd, data, 10);
if (ret == -1) {
    char const* message = strerror(errno);
    printf("failed to write: %s", message);
}

This method is established as a method mainly used by C language programmers, and based on this experience of the lecturer, it is inferred that -1 should be returned, not other values other than 0.


2022-09-22 19:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.