Styles of main functions in C [duplicate] - c

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.

Related

What is the difference of all main functions? [duplicate]

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).

The return type of main() function [duplicate]

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.

Why do C programs return an int?

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.

Return type of main function [duplicate]

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

Is It Necessary to Return a Value in Main()?

I was just writing a quick program for calculating some things when I came across the return statement/exit statement for the C program.
I declared main() to be of type int, so I would have to put in a return of an integer, or my program would not compile correctly. However, is it acceptable to make main a Boolean or even void?
I know the standard way to create a C program is to return a value so any problems can be sorted out, among other things, but wouldn't a Boolean work the same way? Also, could I get away with declaring it void and not having problems with the operating system still running my program after it has been terminated?
Thanks for any and all help.
The C99 standard says: (§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[]) { /* ... */ }
or equivalent; or in some other implementation-defined manner.
So in a hosted environment, int is the only valid, standard return type. Implementations can define other entry points though.
Note that section §5.1.2.2.3 Program Termination has this:
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; 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.
So you omitting a return from main is legal in C99, as long as your main returns an int.
(But previous versions of the C standard didn't have that exception for main - returning no value (or reaching the final } without a return statement) causes "the termination status returned to the host environment [to be] undefined.".)
Summary: You don't necessarily have to, but you should.
In C90, reaching the end of main() without executing a return statement means "the termination status returned to the host environment is undefined". On at least one system I've used, the status returned is 1, which on that system indicate that the program failed.
C99 added a new rule, saying that reaching the end of main() returns 0. (C++ has the same rule.) Not all compilers fully implement C99, and those that do often don't behave as conforming C99 compilers by default. (Added 10 years later: The conformance situation is better now, and most modern C compilers support at least C99.)
The only portable values you can return from main() are 0, EXIT_SUCCESS, and EXIT_FAILURE (the latter two are defined in <stdlib.h>. 0 and EXIT_SUCCESS indicate that the program succeeded (and EXIT_SUCCESS is usually defined as 0); EXIT_FAILURE indicates that the program failed. return 1; is common, but non-portable; I've worked on a system (VMS), where a termination status of 1 indicates success. If you want your program to be portable, use EXIT_FAILURE to indicate failure; that's what it's for. Some systems and program define other system-specific or application-specific status codes.
For portability (and, IMHO, style), it's best to do an explicit return 0; at the end of main(), though it's not required in all circumstances. It's much easier to add that one line of code (which is, at worst, harmless) than to waste time determining whether you need it.
(Update 10 years later: I no longer think it's important to do an explicit return 0; unless you have a requirement for your code to work with old compilers or with current compilers configured to conform to the old C90 standard.)
Note that the correct definitions for main() are:
int main(void) { /* ... */ }
and
int main(int argc, char *argv[]) { /* ... */ }
or equivalent (for example, you can write char **argv rather than char *argv[]). It's questionable whether int main() { /* ... */ } is valid, for subtle reasons I won't go into here, but I believe all compilers accept it. Again, it's easier to add the void keyword than to waste time determining whether you need it.
A lot of books and tutorials use void main() or void main(void). A particular compiler may choose to permit this, but it's not portable. Seeing void main in a book or tutorial is a good sign that the author doesn't know the C standard very well, and that you should find something else to study.
Here is a link that might be of interest. Seems the answer to your question is not that straight. I've also seen compilers (MS Visual C) accepting void as a return type.
The code that calls main() expects it to return int (or call exit()). You cannot change the code that calls main() (it is part of the OS or runtime), so you'd better return int.
The standard, per ISO, is to return an int. See section 5.1.2.2.1 of this document: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf. Also interesting is Stroustrup's commentary on this matter related to both C and C++: http://www2.research.att.com/~bs/bs_faq2.html#void-main.
The return type must be int, as covered by other answers. However your assumption that you must return a value at all because of this is wrong, main is an exception. The C99 standard provides for this, so it is perfectly fine to implement main without using return.
In ANSI C, main () usually has a return type of int, but it can actually be implementation-defined; this means that different compilers and platforms accept different signatures, but int main () and int main (int, char**) are guaranteed by the standard to be well-formed.
It is unlike other non-void functions, in that it doesn't need a return statement. In the case that none is supplied, and the return type is specified as int, then the program is compiled as if there were an implicit return 0; after the last statement in main ().
The relevant part of the standard:
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; 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.
Don't quote me on this, but in K+R, however, things were a little looser, and I think you didn't even need to specify a return type, so main () { } is actually a valid K+R program.

Resources