0

I just wanna know what happens internally when we return a value. If we dont return a value what are the consequences?

#include <stdio.h>
int main() {
  printf("Hello world");
  return 0; //what is use of this?
} 
Pavan Yalamanchili
  • 11,851
  • 2
  • 31
  • 54
sharik sid
  • 21
  • 6
  • it's useful to know if something is success or failure and you can do that based on the exit status of a program. – Ryan McCullagh Feb 17 '17 at 01:15
  • when someone runs your program they can access the return code. In linux you can do this: `echo $?` to see what the program that you just ran returned. – bruceg Feb 17 '17 at 01:16
  • Nothing happens *internally*, because when you return from main() your program is finished. The return value of main() is useful *externally* when your app is finished. – Ken White Feb 17 '17 at 01:17
  • Consider the shell snippet: `if ./a.out; then echo "my program was successful!"; else echo "my program failed"; fi`. The value returned by your program (which I presume is compiled into `a.out`) determines which branch is taken. – William Pursell Feb 17 '17 at 01:21
  • *If we dont return a value what are the consequences?* You cannot avoid returning a value from `main`. This is the one function where, if you don't, the compiler will add it in for you. – Weather Vane Feb 17 '17 at 01:30

3 Answers3

1

it can be evaluated by the system to determine if a program failed to run (and why it failed)

dstorey
  • 68
  • 6
0

I think perhaps you have two questions:

Why does main() return int and not void?

This question has already been answered in many forms. Basically: for the program that called it (a shell, perhaps, or your IDE), so that it can distinguish between success and various modes of failure.

What happens if you forget to return a value from main()?

In the first standardized version of C (C89) there was nothing special about main() in this respect. If you forgot to return a value, the behavior was undefined. In practice, most compilers will act as if you had put return 0;.

Since C99, if you do not return a value from main() explicitly, then main() is defined to return 0. main() is special in this way; other functions do not implicitly return anything.

As Weather Vane said in the comments, your program can't not return a value (on platforms where "return value" is a meaningful concept). On Linux, execve() and similar functions return an int that is the return value of the program. If a program were ill-behaved and did not intend to return a value, the return value would probably just be some arbitrary value (but it's possible that on another platform such a program would crash).

Community
  • 1
  • 1
trentcl
  • 17,886
  • 5
  • 37
  • 60
-1

Not every program or function returns a value. In c, we use return 0 in order to give back control to the operating system when the program is finished running and also to make sure that the program runs smoothly. Hope that helps. Cheers

Mekanic
  • 61
  • 9