Amit
Amit

Reputation: 7818

Compiling simple program doesn't work

I have the following C program (as simple as it gets):

#include <stdio.h>

main()
{
printf("Test");
}

But using the gcc compiler within Cygwin, I cannot get this program to work unless I make the following modifications:

#include <stdio.h>

int main()
{
    printf("Test");
    return 0;
}

Could anyone explain why? What is so special about the "int" and the "return 0;" ?

Thanks! Amit

Upvotes: 1

Views: 1325

Answers (4)

Fred Foo
Fred Foo

Reputation: 363487

int is the required return type for main per the C standard.

Upvotes: 1

jmpcm
jmpcm

Reputation: 1852

intis the return type for the function, in this case the main(). As you know, you always need to specify the return type of a function in C (it could be void; there you don't need to return anything)!

When your function has a return type (int, for example), you are obligated to put a return sentence (return 0;, for example). In C, is a "standard" to return 0 when a function executed correctly. Also, when you run your program, you can obtain the value returned after the execution (in this case it will be 0). If the execution of your program would terminate erroneously, then you could return any other value (-1, 1, 2, etc.) and it is easier for you to detect the error and debug it.

Upvotes: 0

Alex
Alex

Reputation: 2013

The int is a return code. I believe C defaults to returning 0. Generally speaking a return of 0 means successful completion of program while 1,2,3... would be error codes. It is often used by programs that want to test if the program ran successfully.

Upvotes: 0

Wolph
Wolph

Reputation: 80011

With C you are always required to specify your output type. So the int is always required (with some compilers, void will work too).

The "normal" minimal version is this:

int main(int argc, char **argv){
    return 0;
}

Depending on your system you could also have a char **envp and char **apple there aswell.

http://en.wikipedia.org/wiki/Main_function_(programming)#C_and_C.2B.2B

Upvotes: 2

Related Questions