1

While reading the K&R 2nd edition I noticed that the programs always began with "main(){". I had always thought that main() had to have int or void before it. So that it would look like "int main()" or "void main()". What is just "main()" and what is the difference?

bab
  • 2,119
  • 3
  • 28
  • 49
  • possible duplicate of [C function syntax, parameter types declared after parameter list](http://stackoverflow.com/questions/1585390/c-function-syntax-parameter-types-declared-after-parameter-list) – dirkgently Jun 16 '12 at 22:22
  • 3
    `void main()` is simply wrong. – asaelr Jun 16 '12 at 22:39

3 Answers3

8

main() is the old K&R style where the int was omitted as the return type defaults to int if not specified (you should specify it). Additionally, empty parentheses is in K&R style to show it takes no arguments.. in C99 this should now be void to indicate such. Empty parentheses means that the function will accept any number of arguments of any type, which is clearly not what you want. So the final result is:

int main(void) { ... }

main() should return int.. convention says a return 0; statement at the end will help indicate to the caller that the program executed successfully - non-0 return values indicate abnormal termination.

A more direct answer to your question would be that main() { ... } works because it's not wrong. The compiler sees that no return type was declared for the main function so it defaults to int. The empty parentheses indicates to it that main takes any number of arguments of any type, which is not wrong either. However, to conform to C99 style/standard, use

int main(void) { ... }
adelbertc
  • 7,270
  • 11
  • 47
  • 70
  • 1
    Note that empty parentheses means *any amount of arguments of any type* while `void` means 0 argument. – user703016 Jun 16 '12 at 22:21
  • Ah yes, forgot to mention that. Changed. – adelbertc Jun 16 '12 at 22:22
  • @Cicada: This is not entirely true. The empty parentheses merely avoid prototyping the function, so that calls with the wrong number of arguments are not a constraint violation. In the function definition, however, it still defines a function with no arguments, and even though including arguments when calling the function would not be a constraint violation (since there's no prototype in scope), it would still invoke undefined behavior if the call ever took place. – R.. GitHub STOP HELPING ICE Jun 16 '12 at 22:50
0

Because this is supported in by an old version of c.

main()

is equivalent to

int main()
ob_dev
  • 2,808
  • 1
  • 20
  • 26
-4

Syntax most of times depends on the compiler. For example, when you use visual c++ you write "void main" but when you use GCC, you should write "int main()" and then return 0 or 1 if the program finished good or bad.