-2

I wrote my firs C program today. and it looks like this

#include <stdio.h>

int main()
{
    // my first program
  printf("Hello, World\n");
  return 0;
}

thing is, if I run the same thing without return, it gives me the same answer. so my question is, why do I need to write return ? and is it okay to never write it

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Are you specifically asking about the special case of `main` function or about `return` in general? – Gerhardh Aug 03 '22 at 08:58
  • The C committee made the `return` statement at the end of `main()` (**only at the end of `main()`**) optional in C99. In its absence the program behaves as if a statement of `return 0;` was there, You need to use the statement if your compiler is set for an older version of the language. If your code is going to be compiled by *everybody* (if it's public on the internet), don't take risks and, if possible, support older versions of C by including the return statement anyways. – pmg Aug 03 '22 at 08:59

2 Answers2

1

From the C Standard (5.1.2.2.3 Program termination)

1 If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument;11) reaching the } that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified.

So this program

#include <stdio.h>

int main()
{
    // my first program
  printf("Hello, World\n");
}

in fact is equivalent to

#include <stdio.h>

int main()
{
    // my first program
  printf("Hello, World\n");
  return 0;
}

This rule is valid only for the function main.

Otherwise if a function has a return type other than void its return statement shall return a value convertible to the return type.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

The return value here is used as a process exit code by returning 0. For example, if you wrote anything after the return it would not be run. By default at the end of main it will "return 0" which is why the program works without it.

Hope this helps :)