You are here:

C/main() function in C

Advertisement


Question
I’m a beginner in C and since now I’ve made just a few simple exercises. I have a question, if you can help me, please! I’ve read about different ways to write the main() function in C. At school they teach us to use void main(void), which I’ve read is bad. Since then I use int main(int) because I saw that on a website. Is that correct? Should that return an integer? What if the variables and the result are float?

Thank you!


Answer
Hello Stefany.

There are 2 correct versions of the main function that are used most often and that you should know. Both return an integer.

int main(void)

and

int main(int argc, char** argv)

The argc is the count of the command line arguments, including the name of the program, which is the first argument.
The argv is an array of C strings containing the arguments.

Another variant is:

int main(int argc, char* argv[])
Here argv is also an array of C strings. In C, and array can be represented as a pointer and that is why we have the 2 variants.

Other programming environments might add an array of environment variables, but that is rarely used.

The main can only return an integer and the return value is supposed to show something about the success of the program, in case the caller wants to know. Generally programs return a 1 or 0 to indicate success or failure.

See also http://en.wikipedia.org/wiki/Main_function_%28programming%29#C_and_C.2B.2B

Best regards
Zlatko

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.