-2

I am working in the C programming language. What is the function of main()? What is void main() and int main()?

Ronan Boiteau
  • 8,035
  • 6
  • 32
  • 47
Nirmal DC
  • 5
  • 2
  • You should read books for this – Keren Caelen May 04 '18 at 09:49
  • `main`is the start of the user code. It is where your program starts. Lookup `main` in the cmpiler manual or on-line. – Paul Ogilvie May 04 '18 at 09:49
  • Possible duplicate of [Difference between int main() and int main(void)?](https://stackoverflow.com/questions/12225171/difference-between-int-main-and-int-mainvoid) – msc May 04 '18 at 09:50
  • `main()` is the defined start point for all C programs - the first user-defined function called when a program starts. `int main()` is specified in the standard. `void main()` is a non-standard extension supported by some compilers. – Peter May 04 '18 at 09:50

3 Answers3

1

It is the entry point of a C program. See here:

https://en.wikipedia.org/wiki/Entry_point#C_and_C++

Doug
  • 584
  • 4
  • 20
1

What is the function of main()?

It is the entry point of your program. That's the first function which is executed when you run your program.


What is the difference between void main() and int main()?

  • The valid syntax for the main() function is:

    int main(void)
    

    It can also take arguments. See more here.

  • The second syntax is not valid:

    void main(void)
    

That's because your main() should return the exit status of your program.

Ronan Boiteau
  • 8,035
  • 6
  • 32
  • 47
  • what is the role of main() function in programming? – Nirmal DC May 04 '18 at 10:00
  • Since it's the entry point, you will use it to write the base of your program. Call your other functions, etc. – Ronan Boiteau May 04 '18 at 10:04
  • thanks.Why int main is valid syntax and void main is invalid syntax ? – Nirmal DC May 04 '18 at 10:10
  • @NirmalDC Because `void main()` means that `main()` won't return anything. So you can't do `return 0` (or any other exit status). Your `main()` needs to be defined with `int main()` so that you can return an exit status. – Ronan Boiteau May 04 '18 at 10:12
1

Best answer of Brian-Bi:

  • void main() { ... } is wrong. If you're declaring main this way, stop. (Unless your code is running in a freestanding environment, in which case it could theoretically be correct.)
  • main() { ... } is acceptable in C89; the return type, which is not specified, defaults to int. However, this is no longer allowed in C99. Therefore...
  • int main() { ... } is the best way to write main if you don't care about the program arguments. If you care about program arguments, you need to declare the argc and argv parameters too. You should always define main in this way. Omitting the return type offers no advantage in C89 and will break your code in C99.
msc
  • 30,333
  • 19
  • 96
  • 184