Alex Rivera | Logout

Why would you precede the main() function in C with a data type?

Asked 2010-05-23T17:54:40.317
14

Many are familiar with the hello world program in C:

#include <stdio.h>

main ()
{
    printf ("hello world");
    return 0;
}

Why do some precede the main() function with int as in:

int main()

Also, I've seen the word void entered inside the () as in:

int main(void)

It seems like extra typing for nothing, but maybe it's a best practice that pays dividends in other situations?

Also, why precede main() with an int if you're returning a character string? If anything, one would expect:

char main(void)

I'm also foggy about why we return 0 at the end of the function.

Edit
Report

2 Answers

1

The "int" before the main function declaration is the return type of the function. That is, the function returns an integer.

From the function, you can return a piece of data. It is typical to return "0" if the function completed successfully. Any other number, up to 255 is returned if the program did not execute successfully, to show the error that happened.

That is, you return 0, with an int data type, to show that the program executed correctly.

answered 2010-05-23T18:00:24.330
1

It is traditional to use int main(int argc, char * argv[]) because the integer return can indicate how the program executed. Returning a 0 indicates that the program executed successfully, whereas a -1 would indicate that it had a failure of some sort. Usually, the exit codes would be very specific and would be used as a method of debugging since exceptions (in the C++ sense) don't exist in C.

answered 2010-05-23T18:00:49.820

Your Answer