I have been advised by many people that it is better to use integer return type for main function instead of void ! I actually dont understand what return 0 means .. main returns 0 value to program ! What does that mean ?! Could you please help me understand the concept?

void main()
{
body
}
int main()
{

body 
return 0;
}

Recommended Answers

All 4 Replies

They are mainly used for exit codes, similar to the EXIT_SUCCESS and EXIT_FAILURE terms.

By nature they don't really do anything, but if a program has errorcodes defined, you can use them to find out what happened when the program quits. (Whether it quit properly or whether it didn't manage to complete a task)

Some compilers might even not compile your app properly when you use ''void main()'' and supply a warning. Others will work without complaining but the 'results' are unknown. (In general I don't think it hurts all that much if you use void instead of int, but I haven't tested it.)

More information:
MSDN Microsoft for C#: Main() Return Values

Int return codes help answer the important question:

I ran the program, but did it finish normally, throw an error, or get caught in an endless loop of some sort?

By custom, a zero return indicates a successful program run. Other numbers might correspond to specific errors, and no return indicates the program is either still running, or has quit without returning a known error.

I have been advised by many people that it is better to use integer return type for main function instead of void !

That is good advice if you want the code to be maximally portable without any changes.

I actually dont understand what return 0 means

It means the same thing it means when you call a function with a return value.

#include <stdio.h>

int function() {
    return 0;
}

void main() {
    if (function())
        puts("0 was returned");
}

The only difference is the operating system calls main(), and the operating system uses the return value when main() returns.

I have been advised by many people that it is better to use integer return type for main function instead of void ! I actually dont understand what return 0 means .. main returns 0 value to program ! What does that mean ?! Could you please help me understand the concept?

void main()
{
body
}
int main()
{

body 
return 0;
}

By returning 0 or EXIT_SUCCESS in main the program indicates that it exited normally.
Why do we use this?

Consider if your C program is part of a shell script or batch file that executes in sequence with other programs..How do you know if your C program ran correctly? By checking the exit code.

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.