This question already has answers here:
What are the valid signatures for C's main() function?
(5 answers)
Closed 3 years ago.
What is the difference between main, void main and int main in C? what does each one of them do?
Also what is return 0; used for? i know it somehow tells the OS that the program finished succesfully but what does that have to offer?
I would like to note that ive been working on C for a little more than a month so im not really experienced
5.1.2.2.1 Program startup
1 The function called at program startup is named main. The implementation declares no
prototype for this function. It shall be defined with a return type of int and with no
parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be
used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;10) or in some other implementation-defined manner.
10) Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as
char ** argv, and so on.
C 2011 Online Draft
main() is equivalent to int main(void). Under earlier versions of the language, if you defined a function without an explicit return type, the compiler assumed it returned int. Also, if you define a function without any parameters, that means the function takes no parameters. Implicit typing is no longer allowed, and using prototype syntax allows you to catch errors in the number and types of arguments at compile time, so this form should no longer be used.
void main() is not standard, and should not be used unless your implementation explicitly documents it as a valid signature for main ("or in some other implementation-defined manner")1. Otherwise, using it results in undefined behavior, which may result in your code misbehaving on startup or exit. There are platforms where it runs with no apparent issues, but you shouldn't rely on that being true.
5.1.2.2.3 Program termination
1 If the return type of the main function is a type compatible with int, a return from the
initial call to the main function is equivalent to calling the exit function with the value
returned by the main function as its argument;11) reaching the } that terminates the
main function returns a value of 0. If the return type is not compatible with int, the
termination status returned to the host environment is unspecified.
11) In accordance with 6.2.4, the lifetimes of objects with automatic storage duration declared in main
will have ended in the former case, even where they would not have in the latter.
C programs return a status code to the runtime environment - on *nix and similar platforms, a return code of 0 indicates successful, normal program termination. stdlib.h defines the macros EXIT_SUCCESS and EXIT_FAILURE, which should be used instead of literal numeric values:
#include <stdlib.h>
...
int main( void )
{
...
if ( something_bad_happens )
return EXIT_FAILURE;
...
return EXIT_SUCCESS;
}
Even then, I wouldn't use it, because it's guaranteed to be non-portable.
The difference between them is that void main() is not a valid signature for the main function according to the standard. According to the standard, there are only two valid signatures, and those are:
int main(void)
int main(int argc, char *argv[])
A compiler may allow other signatures, but it is not required by the standard. One common non-standard signature is:
int main(int argc, char *argv[], char *env[])
The return statement simply returns an integer that can give information to the caller. If you're in a linux environment, you can inspect this value like this:
$ ./a.out
$ echo $?
In the bash shell, the variable $? contains the return value of the last exectuded command.
You can read more about main signatures and return values here: https://port70.net/~nsz/c/c11/n1570.html#5.1.2
int main is the only valid way to declare the main() function, the others are wrong. You can optionally specify parameters int main(int argc, char *argv[]), but the return type int is required.
The return value of the main() function is used to tell the calling application how the program ended. Returning 0 means that the program completed successfully, while non-zero values are used to indicate some kind of error. This is typically tested in shell scripts. You can also call the exit() function to end the program, its argument will be used as the exit status the same way (this allows terminating the program from inside functions).
Related
This question already has answers here:
What should main() return in C and C++?
(19 answers)
Closed 9 years ago.
I get this code:
#include<stdio.h>
#include<stdlib.h>
void main(void)
{
char *ptr = (char*)malloc(10);
if(NULL == ptr)
{
printf("\n Malloc failed \n");
return;
}
else
{
// Do some processing
free(ptr);
}
return;
}
It compiles successfully in Visual C, but do not compile in gcc, I get "error:'main' must return 'int'". So is the return type 'int' of main() function is a convention(which is for compiler to define), or a rule of C?
The C standard (ISO/IEC 9899:2011) says:
5.1.2.2.1 Program startup
1 The function called at program startup is named main. The implementation declares no
prototype for this function. It shall be defined with a return type of int and with no
parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be
used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;10) or in some other implementation-defined manner.
10) Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as
char **argv, and so on.
Thus, the only portable declaration for main() has a return type of int. If MSVC defines that void is permitted ('or in some other implementation-defined manner'), so be it, but do not expect the code to be portable. The old versions of the Microsoft compilers (up to and including MSVC 2005) do not permit void main(): see the documentation at main: Program startup and The main Function and Program Execution. However, MSVC 2008 and later are documented to allow void main(): see main: Program Startup. The three-argument form of main() is noted as a common extension in Appendix J:
J.5 Common extensions
The following extensions are widely used in many systems, but are not portable to all
implementations. The inclusion of any extension that may cause a strictly conforming
program to become invalid renders an implementation nonconforming. Examples of such
extensions are new keywords, extra library functions declared in standard headers, or
predefined macros with names that do not begin with an underscore.
J.5.1 Environment arguments
In a hosted environment, the main function receives a third argument, char *envp[],
that points to a null-terminated array of pointers to char, each of which points to a string
that provides information about the environment for this execution of the program
(5.1.2.2.1).
The value returned from main() is transmitted to the 'environment' in an implementation-defined way.
5.1.2.2.3 Program termination
1 If the return type of the main function is a type compatible with int, a return from the
initial call to the main function is equivalent to calling the exit function with the value
returned by the main function as its argument;11) reaching the } that terminates the
main function returns a value of 0. If the return type is not compatible with int, the
termination status returned to the host environment is unspecified.
11) In accordance with 6.2.4, the lifetimes of objects with automatic storage duration declared in main
will have ended in the former case, even where they would not have in the latter.
Note that 0 is mandated as 'success'. You can use EXIT_FAILURE and EXIT_SUCCESS from <stdlib.h> if you prefer, but 0 is well established, and so is 1. See also Exit codes greater than 255 — possible?.
7.22.4.4 The exit function
¶5 Finally, control is returned to the host environment. If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If the value of status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.
According to c standard main() should return integer for informing success or failure.Generally for success it returns zero and for failure it returns a integer value(either positive or negative).
Generally main is declared as
int main(void);
so it expects integer as return type.
If command line arguments are there,
int main(int argc,char *argv[]);
void main() is non-standard C and int main() is the standard.
I usually get a warning from the compiler if I tell it to return anything else.
This is the exit code provided to whoever called your program. Non-zero value usually signifies error.
Short answer: because that's what the C standard says:
5.1.2.2.1 Program startup
1 The function called at program startup is named main. The implementation declares no
prototype for this function. It shall be defined with a return type of int and with no
parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be
used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;9) or in some other implementation-defined manner. (emphasis mine)
The C standard demands it because there's no mechanism to communicate to the environment that you'll be returning something else than an integral value. Therefore, int is the only possible type; it covers all platforms and the expected numeric ranges they expect the process to return to them.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What should main() return in C/C++?
Difference between void main and int main?
I have always been using the main method in C like
void main(){ // my code }
and it works pretty well for me.
I also know about the other int return type:
int main(void)
int main()
int main(int argc, char *argv[])
But I have not been able to find any resource that says that I can use void as a return type. Every book suggests that the return type must be int or else it be omitted. Then why does void main() work?
Is this dependent on the version of C that I am using? Or does it work because I use a C++ IDE? Please reply specific to C and not C++.
Only book authors seem to be privy to the place where a return type of void for main() is allowed. The C++ standard forbids it completely.
The C standard says that the standard forms are:
int main(void) { ... }
and
int main(int argc, char **argv) { ... }
allowing alternative but equivalent forms of declaration for the argument types (and the names are completely discretionary, of course, since they're local variables to the function).
The C standard does make small provision for 'in some other implementation defined manner'. The ISO/IEC 9899:2011 standard says:
5.1.2.2.3 Program termination
If the return type of the main function is a type compatible with int, a return from the
initial call to the main function is equivalent to calling the exit function with the value
returned by the main function as its argument;11) reaching the } that terminates the
main function returns a value of 0. If the return type is not compatible with int, the
termination status returned to the host environment is unspecified.
11) In accordance with 6.2.4, the lifetimes of objects with automatic storage duration declared in main
will have ended in the former case, even where they would not have in the latter.
This clearly allows for non-int returns, but makes it clear that it is not specified. So, void might be allowed as the return type of main() by some implementation, but you can only find that from the documentation.
(Although I'm quoting C2011 standard, essentially the same words were in C99, and I believe C89 though my text for that is at the office and I'm not.)
Incidentally, Appendix J of the standard mentions:
J.5 Common extensions
The following extensions are widely used in many systems, but are not portable to all
implementations. The inclusion of any extension that may cause a strictly conforming
program to become invalid renders an implementation nonconforming. Examples of such
extensions are new keywords, extra library functions declared in standard headers, or
predefined macros with names that do not begin with an underscore.
J.5.1 Environment arguments
In a hosted environment, the main function receives a third argument, char *envp[],
that points to a null-terminated array of pointers to char, each of which points to a string
that provides information about the environment for this execution of the program
(5.1.2.2.1).
Why does void main() work?
The question observes that void main() works. It 'works' because the compiler does its best to generate code for programs. Compilers such as GCC will warn about non-standard forms for main(), but will process them. The linker isn't too worried about the return type; it simply needs a symbol main (or possibly _main, depending on the system) and when it finds it, links it into the executable. The start-up code assumes that main has been defined in the standard manner. If main() returns to the startup code, it collects the returned value as if the function returned an int, but that value is likely to be garbage. So, it sort of seems to work as long as you don't look for the exit status of your program.
From the horse's mouth:
5.1.2.2.1 Program startup
1 The function called at program startup is named main. The implementation declares no
prototype for this function. It shall be defined with a return type of int and with no
parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be
used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;9)
or in some other implementation-defined manner.
9) Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as
char ** argv, and so on.
The loophole is the "some other implementation-defined manner". An implementation may allow main to return void (or any other type), but it must explicitly document that such a signature is allowed. Otherwise the behavior is undefined, meaning the compiler can do anything it wants. The program may execute without any problems. It may execute, but leave the environment in a bad state. It may crash on exit. It may fail to load at all.
It is dependent on the compiler you are using, but void main is not compilable everywhere. I have seen compilers that won't compile a program with void main. I can not recall the particular case(for c), but I know for sure this happens in g++(yes I know this is c++).
The standard calls for main() to return int, but a lot of C compilers allow you to specify the return type of main() as void.
I recommend you get into the habit of returning int. Adding a
return 0;
to the end of your main() isn't too much effort.
I was acceptable in C89 but it is no longer considered "safe". Under C99, it is no longer acceptable.
http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?id=1043284376&answer=1044841143
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the proper declaration of main?
I am working on my C skills and I have noticed that
int main( int argc, char *argv[] )
and
return (EXIT_SUCCESS)
instead of
int main() and return 0
Why is this?
If you are going to ignore the argument list, it is reasonable and sensible to use:
int main(void) { ... }
The standards bless this usage, as well as the one with arguments. You get a warning from GCC if you compile with -Wstrict-prototypes and don't include the void, so I write the void. C++ is different here.
As for return EXIT_SUCCESS;, there seems to be little benefit to it in general; I continue to write return 0; at the end of a main() function, even though C99 permits you to omit any return there (and it then behaves as if you wrote return 0;).
ISO/IEC 9899:1999
§5.1.2.2.1 Program startup
¶1 The function called at program startup is named main. The implementation declares no
prototype for this function. It shall be defined with a return type of int and with no
parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be
used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;9) or in some other implementation-defined manner.
9) Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as
char ** argv, and so on.
§5.1.2.2.3 Program termination
¶1 If the return type of the main function is a type compatible with int, a return from the
initial call to the main function is equivalent to calling the exit function with the value
returned by the main function as its argument;10) reaching the } that terminates the
main function returns a value of 0. If the return type is not compatible with int, the
termination status returned to the host environment is unspecified.
10) In accordance with §6.2.4, the lifetimes of objects with automatic storage duration declared in main
will have ended in the former case, even where they would not have in the latter.
§7.20.4.3 The exit function
¶5 Finally, control is returned to the host environment. If the value of status is zero or
EXIT_SUCCESS, an implementation-defined form of the status successful termination is
returned. If the value of status is EXIT_FAILURE, an implementation-defined form
of the status unsuccessful termination is returned. Otherwise the status returned is
implementation-defined.
Aside: Note that §5.1.2.2.3 clearly indicates that the C standard allows an implementation to permit return types for main() other than int (unlike the C++ standard, which expressly forbids a return type other than int). However, as Jens rightly points out, a non-int return type from main is only allowed if the implementation explicitly documents that it is allowed, and the documentation will probably place limits on what is allowed.
int main (int argc, char * argv []) is for when you want to take command line arguments.
EXIT_SUCCESS is just a #define that's more descriptive than 0.
int main( int argc, char *argv[] ) allows the user input arguments at the execution of the program, i.e., that text you write in the console after the program name.
return (EXIT_SUCCESS) is in case an O.S. doesn't expect 0 as a value of successful exit: it would be any other value, but in most cases, EXIT_SUCCESS equals 0.
Operating Systems can differ in how a program indicates successful operation. The macro EXIT_SUCCESS ideally expands to a value appropriate for the system the program is compiled for.
http://en.wikipedia.org/wiki/Exit_status
(The two things you ask have nothing to do with each other.)
To answer your first question:
Having int main() just means that the program is not accepting command line arguments.
When it takes the two arguments, argc is the argument count (it will always be greater than or equal to one, since the first argument will be the path or name of the program itself), and argv is the list of arguments.
To answer your second question:
EXIT_SUCCESS is guaranteed to be interpreted as success by the underlying operating system.
This question already has answers here:
What should main() return in C and C++?
(19 answers)
Closed 7 years ago.
Can anyone tell me the difference between int main() and int main(void)? Why do both of them work and what is the default argument to int main()?
No difference under ordinary circumstances. This is no 'default argument to main()', since it has no arguments at all.
Here's the un-ordinary circumstance. If you write your own call to main, then () will permit you to pass it any parameters you like, while (void) will force you to pass it none. Still, none of this matters in terms of the 99.99999999% case, which is main being invoked by the runtime to launch your program. The runtime neither knows nor cares if you write () or (void).
If you code the standard int main(int argc, char **argv) you will get your command-line parameters in there.
main() allows you to call main with any number of parameters. main(void) forces you to call main with no parameters. So:
main(foo, bar);
Is fine with main() but not with main(void) - the compiler generates an error.
Now if you're specifically asking about the program's entry point, it doesn't really make a difference; in either case, you won't have the arguments to the program (argc, argv, envp) available.
From a practical viewpoint, there's no real difference. With int main(void), you're explicitly stating that main takes no parameters, so you can't invoke it with any. With int main(), you're leaving open the possibility of invoking main with some parameters.
However, except in strange situations like code golf or intentionally obfuscated code, you don't invoke main anyway -- it's the entry point to the program, so it's automatically invoked by the startup code. The startup code will pass the command line arguments anyway, so your choices don't change how it's invoked, only whether you use or ignore the parameters that get passed.
The standard does specifically allow you to define main with or without parameters (§5.1.2.2.1/1):
The function called at program startup is named main. The implementation declares no
prototype for this function. It shall be defined with a return type of int and with no
parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be
used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;
Though it's outside the tags specified, in C++ the situation is slightly different. In C, a function declaration like:
int f();
specifies that f is a function returning an int, but gives no information about the number or type of parameters f might expect (this is included primarily for compatibility with old code -- at one time, this was the only way to declare a function in C). In C++, that same declaration explicitly declares f as a function that takes no parameters, so attempting to invoke f with one or more parameters cannot invoke this function (it must either invoke another overload or produce an error if no suitable overload is found).