Why do C programs return an int? - c

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.

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.

Is this code valid under any C standard?

Does this code follow C standards (e.g. C89, C99, C10x)?
void
main(int a,int b, int c, int d,char *msg){
if(d==1){
printf("%s\n",msg);
}else{
main(1,2,3,1,&"Hello Stackoverflow");
}
}
If not, why?
There's one error: &"Hello Stackoverflow" does not have type char*, so you shouldn't pass that to a function expecting that type.
Apart from that, this program is allowed by the Standard as an implementation-specific extension, but a compiler has the freedom to decline it.
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.
(2011 Standard, latest draft section 5.1.2.2.1, emphasis added.)
There is no ban on recursive calls to main in the C Standard. This is a difference with C++, which does outlaw that.
You mean beside it won't run? main is defined to take int, char** as arguments.
Depending on the compiler, this either will fail to start up as the run-time can't find main(int, char**), or on older compilers it'll just crash because it piddles on the stack.
It's only valid under C99 and later if the implementation explicitly documents that main may take 5 parameters (4 int and 1 char *) and return void (that's the "or in some other implementation-defined manner" clause that larsmans referenced in his now-un-deleted answer, and I don't think that clause was present in C89).
Otherwise the behavior is undefined, meaning the compiler may or may not choke on it.

Can the function main in C return a pointer?

As the heading goes, Is it possible for the main function return a pointer? If yes then where would be useful? Thanks!
Only a return type of int is blessed by the standard:
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.
C11 draft, April 12, 2011
Everything else is up to your compiler and therefore not a C-question anymore.
No. main() returns an int in standard C. The interpretation of this return value is a matter for the surrounding runtime environment. If you know exactly what you're doing, in some kind of specialized situation where you know that the environment is going to interpret the value in a certain way, then you can cast a pointer to an int. But that's nasty.
And be aware that a pointer to dynamically-allocated memory is (probably) meaningless after the program exits anyway! It would only make sense to return a pointer to a fixed address, e.g. a hardware register in some embedded environment.
Completing phresnel's answer, and answering whether it would be useful: since each process has its own address-space, even if your main() returns an integer value that you'd use as an address, what would be the point since the returned pointer is only consistent to the just exited process's address-space...

Styles of main functions in C [duplicate]

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.

Resources