I've noticed a few different ways people write the main() function.

int main{ }

main(void){ }

void main(){ }

I'm confused with what's considered "best practice" or why I'd choose one over the other.
Is there a difference?

thanks!

Recommended Answers

All 5 Replies

Just choose int version. Why? Someone will explain. But according to Salem, void mainers are doomed :D

Use int main(){} . It's standard C, nothing else is. It's the only one guaranteed to work on all C99 compliant systems.

All the post above are true especially have a look at link given by DaveSinkula.Here I will just go with the basics to help you know the concept.

What is main actually ?
Main is the function which is called before all functions when we execute a C or C++ program.So that must mean it should be called by something and it should return something.

So why not void main() ??? That is because main is the function which is called by the operating system through some start up routine and that start up routine decides success or the failure of the program on the basis of the value returned from main.

So now we can say that a return value which is an integer is needed for main as the start up routine calls main as something like this :

exit( main() );

Now for the question which is better int main() or int main(void) ?Both are ok and compilers would consider both calls as right but sometimes it would be better to specify int main( void ) tp tell the compiler right away that we are not taking any values form the command line by specifying "void" in place of arguments to main function.

commented: QC scrutinized, and gladly passed. +6

What is main actually ?
Main is the function which is called before all functions when we execute a C or C++ program.So that must mean it should be called by something and it should return something.

main() might not be a traditional function, just the starting address of the program, that as well might have no return. All implementation dependent, and only in more rare cases obviously.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.