This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What should main() return in C/C++?
What value does this function return. just plain main.
main()
{
...
}
and if a function has two mains , what happens?
What value does this function return.
main needs to be declared as returning an int. The return value is passed to the caller, which is usually the operating system.
5.1.2.2.1 Program startup
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[]) { /* ... */ }
and if a function has two mains , what happens?
Linker reports an error.
In C99/C11, main returns 0 if the } is reached in a hosted environment,. Else, the return value is undefined.
C11, § 5.1.2.2.2 Program execution
[...] reaching the } that terminates the main function returns a value of 0.
Assuming you're using a C89 or earlier compiler, then
main()
{
...
}
returns int. If you're using a C99 or later compiler, it's an error.
As of C99, if you reach the ending } of main without an explicit return, the return value is 0. Not sure about C89 or earlier.
Not sure what "a function has two mains" is supposed to mean. If a program has two main functions defined, then you'll most likely get a duplicate definition error at link time.
Related
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).
This question already has answers here:
Can I omit return from main in C? [duplicate]
(2 answers)
Why do C standards allow you not to return a value from a function?
(5 answers)
What was the rationale for making `return 0` at the end of `main` optional?
(2 answers)
What should main() return in C and C++?
(19 answers)
Closed 3 years ago.
Which is a good practice of int main() declaration in C?
int main(){
stuff;
return 0;
}
or
int main(){
stuff;
}
I have tried searching on the internet and most of them are unclear with some mentioning about compiler stuff. I know that a function should return something. However, both works perfectly normal on my computer. Any help on this topic will be greatly appreciated.
Because many programmers used the second style, causing unspecified exit status to be reported to the system, the C Standard committee decided to make main return 0 implicitly if control leaves its body without a return statement. This behavior is mandated by the C Standard C99 and later versions. As a consequence, return 0; can be omitted by it is better IMHO to still make it explicit.
Note however that it is also considered good style to indent the statements in the body of functions:
int main() {
stuff;
return 0;
}
Note also that the C Standard documents 2 possible prototypes for main:
int main(void);
and
int main(int argc, char *argv[]);
or equivalent variants:
int main(int argc, char **argv[]);
int main(const int argc, char ** const argv);
etc.
Omitting the argument list as you wrote in both examples is supported and would be equivalent to int main(void) in C++, but is not exactly equivalent in C: It means the argument list is unspecified, so the compiler cannot check the arguments passed to main if it encounters a call to main in the program, not can it perform the appropriate conversions.
In this case, it does not matter since the main functions in the examples do not use their arguments and indeed seems more consistent than int main(void) since arguments are indeed passed to it by the startup code.
Both will work, because main is special. There's no difference in the compiled code. The standard guarantees that main returns 0 if it terminates without an explicit return value.
But it's better to be explicit and return 0.
For skeptics, an excerpt from the C standard clause 5.1.2.2.3 (Program termination):
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; reaching the } that terminates the main function returns a value of 0.
Normally it is not allowed for the control flow to reach the end of a non-void function without returning something. The main function is handled differently.Refer the below document page 59 & 62
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2960.pdf:
If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;
This question already has answers here:
What should main() return in C and C++?
(19 answers)
Closed 5 years ago.
So I have a MacBook Pro 2017 and whenever I compile a program that as "void main", the compiler gives me a warning saying that the return type of main is not int...
void main(){
(...)
}
Like the warning says, you should define the return type as an int:
int main() {
// bunch of code...
return 0;
}
Current versions of the C standard require that the main function has a return type of int. So you need to change the definition to int main() and have it return a value.
Section 5.1.2.2.1 of the C standard detailing hosted environments states the following:
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 or in some other implementation-defined manner.
Note that a definition of int main() is allowable as the empty parameter list means the function takes no parameters. From section 6.7.6.3:
14 An identifier list declares only the identifiers of the parameters of the function. An empty list in a function declarator
that is part of a definition of that function specifies that the
function has no parameters. The empty list in a function declarator
that is not part of a definition of that function specifies that no
information about the number or types of the parameters is supplied.
Specifying the main function as void main() is a pre-standardized variant from the K&R days and is no longer valid.
It's expected that main() will return an int value. A minimal start is:
int main() {
return 0;
}
A more formal version which accepts command-line parameters:
int main(int argc, char** argv) {
return 0;
}
Declaring it with a different type makes it incompatible. Some older compilers may not care, but Xcode's does.
C has been around a long time and has evolved considerably from its early days. If you're using an older reference you may find examples with really strange notation, or conventions that are no longer value.
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.
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.