2

In the examples in week 1, we declare the main function as follows:

int main (void)
{
// code 
}

Why do we use int? Is it wrong to use the following instead?

main ()
{
// code
}
1

Yes, it's wrong. According to the c99 standard, the return type of main is "int" and not writing the return type of a function is bad practice. The compiler will assume it's int, but you should write it anyway.

Also, the c standard requires you specify whether or not you're taking any arguments for main. You can write

int main ()

in c++, but you shouldn't in C. That's because in C, leaving the argument field empty in a function's definition doesn't mean that the function doesn't take any arguments, but it means that the function may or may not take any arguments.

0

According to C99 standard:

5.1.2.2.1 Program startup
The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

    int main(void) { /* ... */ }

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

    int main(int argc, char *argv[]) { /* ... */ }

or equivalent; or in some other implementation-defined manner.

So the short answer to your question, is because the standard we use says so.

On the other hand, in C (unlike C++), the type void and the practise of not specifying the type, are not the same thing. A non-type doesn't mean there are not parameters, but the there might be parameters or not. So

main() { /* ... */ }

is not the same as

void main(void) { /* ... */ }

even though it looks like it should. Also if you specify as return type void, that means you can't return 0 if the code exits normally, or another number on error, so there's that.

I hope this made it a little clearer. So your best bet is to follow the standard and just use

int main(void) { /* ... */ }

to be safe and to help readability if you show your code to others.


If this answers your question please accept it by clicking the gray check-mark to the left, so that it becomes green. You can also vote it up by pressing the up arrow above the check-mark. And don't forget to keep coding!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .