This question already has answers here:
What should main() return in C and C++?
(19 answers)
Closed 8 years ago.
I understand why C requires a main function to begin the execution of a program, but of the now three books I've read entirely or in portion, none has explained why programs begin by declaring main as int, or with an argument of void:
int main(void)
can someone tell me what the purpose of this is?
The return value of main() is used to indicate success or failure to its parent process. More generally, it can be used to communicate back specific statuses as well, though C doesn't define those.
If main() returns 0 or EXIT_SUCCESS, then the program was successful. EXIT_FAILURE or non-zero, then it failed.
The void in the parameter list simply says that it takes no arguments. This is because of a (mis)feature of C which allows you to declare a function without fully specifying the paramters it takes. A function declared int func(); can be called with any number of parameters, but int func(void); can only becalled with zero.
Example
on linux,
two trivial programs:
$ cat ret0.c
int main (void) { return 0; }
$ cat ret42.c
int main (void) { return 42; }
Then in `bash` we can look at
$ ./ret0 ; echo $?
0
$ ./ret42 ; echo $?
42
So it's possible to use that status when calling your program.
The int return is there to give an error indicator back to the OS. return 0 means no error, all other codes (typically return 1) indicates the program could not finish successfully. Other programs (e.g., shell scripts) can use this error code to determine if your program executed its task, or ran into a problem.
void just means no arguments. It's the same as
int main()
{
/* program */
}
but more explicit.
A program can take command line arguments, in which case main must be defined as
int main(int argc /* number of arguments */, char *argv[] /* arguments)
{
/* program
}
Any good book on C should explain this.
First off let us forget about main. In C(not C++) if you define a function with no parameters like this
int f(){ return 0;}
It is legal to call such a function with any number of arguments:
int a = f(); /* legal */
int a = f("help", 1, 2.0); /* legal */
If you want your function f to only work with exactly no arguments you can amend it like this:
int f(void){return 0;}
int a = f(); /* legal */
int a = f("help", 1, 2.0); /* not legal as it has too many parameters */
The same thing applies to main() and main(void) . In most cases in the reasonable world most people would never care however I have encountered legal code that calls main within the program.
So declaring main like:
int main() {
/* Do a bunch of stuff here */
}
Allows for code elsewhere in your program to do this:
main();
main(1,2,3,4);
By declaring main(void) you add a compiler check that prevents the latter example main(1,2,3,4) from compiling.
Like any other function in C, main is also a function. Thus it has a return type and can
accept arguments.
int main(void)
Here int is the return type of main. Many people still use 'void' because they do not
update themselves with the current language standards. haccks's answer mentions about
the latest standard specifying the signature of main function.
Its general and good practice to have int as main's return type as it tells the parent process of main about the termination (success / failure) of the program.
Like any other function main is also capable of accepting arguments, but with an exception, i.e. the arguments to main are given before the execution of program starts. These are called "command line arguments".
main can accept arguments in two ways :
1. int main(void)
or
int main()
2. int main(int argc, char *argv[])
or
int main(int argc, char **argv)
The first one says that main is not expecting any arguments where as the second declara-
-tion expects the user to provide command line arguments to main.
Note : main should take either 0 or 2 arguments. If you try to give any number of
arguments other than these then it gives the following warning when you compile your code
warning: ‘main’ takes only zero or two arguments [-Wmain]
Edit : The above warning is displayed if you are using gcc.
Related
This question already has answers here:
Why does c allow main() even when it is not int main() or void main()?
(3 answers)
Closed 2 years ago.
I'm new to programming and was using Visual Studio Code in C language to try out coding. I started with the Hello World function, but, even though the output was correct (the output was "Hello World!"), the following warning appeared. I don't know what it means:
[Running] cd "c:\Users\lucas\OneDrive\Ambiente de Trabalho\" && gcc test.c -o test && "c:\Users\lucas\OneDrive\Ambiente de Trabalho\"test
test.c:3:1: warning: return type defaults to 'int' [-Wimplicit-int]
3 | main(){
| ^~~~
Hello World
[Done] exited with code=0 in 0.71 seconds
I used the code below to get the Hello World output:
#include<stdio.h>
main (){
printf("Hello World!");
}
What should I do to fix this warning?
Thanks for the help!
You need to explicitly give main a return type:
int main( void )
{
printf ("Hello World!");
}
The standard signatures for main are
int main( void )
or
int main( int argc, char **argv ) // you can use different names for argc and argv
That is, either takes 0 or 2 parameters and returns an int.
In the early days of C, if you didn't provide a return type for a function, the compiler assumed it returned int. Such implicit typing is no longer allowed, hence the warning.
All functions must specify a return type. Older version of C would allow the return type to be omitted, in which case the return type defaults to int.
The main function is particular must return int, so explicitly state as much. Also, you need to return a value, and by convension main should return 0 if the program was successful.
#include<stdio.h>
int main ()
{
printf("Hello World!");
return 0;
}
Every function in C needs a return value type. With the main function, it can either be of type void or int. void means that the main function doesn't return a value. int means that the main function returns an integer.
It looks like the compiler automatically filled in that part of your code with int, and it's just letting you know that you should actually be putting some return type.
So you can either do this:
#include<stdio.h>
int main (){
printf("Hello World!");
return 0;
}
Or this
#include<stdio.h>
void main (){
printf("Hello World!");
}
The code given below is an exercise that our teacher gave to prepare us for exams.
We are supposed to find the errors that occur in this code and fully explain them .
#define SIZE 10
int start (void a,int k) {
const int size=10;
char array[size];
char string[SIZE];
mycheck(3,4);
array[0]=string[0]='A';
printf("%c %c\n", array[0], string[0]);
myRec(7);
}
int mycheck(int a , int b) {
if (a==0 || b==0 ) {
return 0;
}
else {
return (a*b);
}
}
int myRec(int x) {
if(x==0)
return 0;
else
printf("%d,",x);
myRec(x--);
}
I have found these errors so far:
1.int start (void a,int k)
explanation: We can't have a variable of type void, because void is an incomplete type
2.const int size=10;
explanation:we can't use variable to define size of array
(problem is when I run it in dev-c++ it doesn't show an error so I'm not sure about this)
3.mycheck(3,4);
explanation: prototype of function mycheck() is not declared, so the function mycheck is not visible to the compiler while going through start() function
4.A friend told me that there is an error in function myRec because of this statement myRec(x--);
(I don't really get why is this an error and how you can I explain it?)
5.Main() function doesn't exist.
I'm not sure about this but if i run the code (in dev-c++) without main function I get a compilation error
I'm not sure if the errors that I pointed out are 100% right or if I missed an error or if I explained them correctly.
Please correct me if any of the above is wrong!
a friend told me that there is an error in function myRec cuz of this
statement myRec(x--);
It will lead to stackoverflow. Due to post-decrement, the actual argument passed to function myRec(), never decreases and therefore the condition:
if(x==0)
return 0;
will never become true. Regarding your rest of the errors, it depends on the compiler version being used:
For example C99, you are allowed to have variable size arrays like this:
const int size=10;
char array[size];
char string[SIZE];
but pre C99, you would have to use malloc or calloc. For your functions used without prototype, most compilers would generate a warning and not error and also due to no #include<stdio.h> statement, your printf would also lead to a warning.i Again, lot of these things are compiler dependent.
1.int start (void a,int k)
explanation: We can't have a variable of type void ,because void is an
incomplete type
Correct.
2.const int size=10;
explanation:we can't use variable to define size of array (problem is
when i run it in dev-c++ it doesnt show an error?so im not sure about
this!)
This is also correct, that char array[size];, where size is not a compile-time constant, is invalid in C89. However, in C99 and newer, this is actually valid and would create a variable-length array. It is possible that your Dev-C++ IDE is using GCC with the language set to C99 or newer, or has GNU C extensions enabled to enable this feature.
3.mycheck(3,4);
explanation: prototype of function mycheck() is not declared.So the
function mycheck is not visible to the compiler while going through
start() function
Correct. This can be fixed either by declaring the function's prototype before the start() function, or just moving the whole function to the top of the file. As noted by Toby Speight in the comments, in C89, this should not actually be a compiler error, since functions are implicitly declared when they are used before any actual declaration as int (), i.e. a function returning int with any arguments, which is compatible with the declarations of mycheck and myRec. It is however bad practice to rely on this, and implicit function declaration does not work in C99 or newer.
4.a friend told me that there is an error in function myRec cuz of this statement myRec(x--);
(I don't really get why is this an error and how you can explain it?)
This function is a recursive function. This means it calls itself within itself in order to achieve a kind of looping. However, this function as it is currently written would run forever and cause an infinite loop, and since it is a recursive function, and needs a new stack frame each time it is called, it will most likely end in a stack overflow.
The function is written with this statement:
if(x==0)
return 0;
This is intended to terminate the recursion as soon as x reaches 0. However, this never happens, because of this line of code here:
myRec(x--);
In C, postfix -- and ++ operators evaluate to their original value before the addition or subtraction:
int x = 5;
int y = x--;
/* x is now 4; y is now 5 */
However, using the prefix version of these operators will evaluate to their new value after adding / subtracting 1:
int x = 5;
int y = --x;
/* x is now 4; y is now 4 */
This means that on each recursion, the value of x never actually changes and so never reaches 0.
So this line of code should actually read:
myRec(--x);
Or even just this:
myRec(x - 1);
5.Main() function doesn't exist ...again im not sure about this but if i run the code (in dev-c++) without main function i get a compilation
error
This one could either be right or wrong. If the program is meant to run on its own, then yes, there should be a main function. It's possible that the function start here should actually be int main(void) or int main(int argc, char *argv[]). It is entirely valid however to compile a C file without a main, for example when making a library or one individual compilation unit in a bigger program where main is defined in another file.
Another problem with the program is that myRec is used before it is declared, just like your point 3 where mycheck is used before it is declared.
One more problem is that the functions start and mycheck are declared to return int, yet they both do not contain a return statement which returns an int value.
Other than that, assuming that this is the entire verbatim source of the program, the header stdio.h isn't included, yet the function printf is being used. Finally, there's the issue of inconsistent indentation. This may or may not be something you are being tested for, but it is good practice to indent function bodies, and indentation should be the same number of spaces / tab characters wherever it's used, e.g.:
int myRec(int x) {
if(x==0)
return 0;
else
printf("%d,",x);
myRec(x--);
}
1) Hello friend your Recursive function myRec() will go infinite because it
call itself with post detriment value as per C99 standard it will
first call it self then decrements but when it call itself again it have
to do the same task to calling self so it will never decrements and new
stack is created and none of any stack will clear that recursion so
stack will full and you will get segmentation fault because it will go
beyond stack size.
2) printf("%d,",x); it should be printf("%d",x); and you should include #include library.
I think your another mistake is you are calling your mycheck() and you
returning multiplication of two integer but you are not catch with any
value so that process got west.So while you are returning something you
must have to catch it otherwise no need to return it.
3) In this you Program main() function missing. Program execution starts
with main() so without it your code is nothing. if you want to execute
your code by your own function then you have to do some process but
here main() should be present.or instead of start() main() should
be present.
4) you can also allocate any char buffer like this int j; char array[j=20];
your code should be like this.
#include<stdio.h>
#define SIZE 10
int mycheck(int a , int b) {
if (a==0 || b==0 ) {
return 0;
}
else {
return (a*b);
}
}
int myRec(int x) {
if(x==0)
return 0;
else
printf("%d",x);
myRec(--x);
}
void main (int argc, char** argv) {
const int size=10;
char array[size];
char string[SIZE];
int catch = mycheck(3,4);
printf("return value:: %d\n",catch);
array[0]=string[0]='A';
printf("%c %c\n", array[0], string[0]);
myRec(7);
printf("\n");
}
Enjoy.............
My textbook mentions: There must be at least one statement in the executable part of main function.
1)
#include <stdio.h>
void main(){ int c; }
2)
#include <stdio.h>
void main(){ int c; c=0; }
The above two codes result in runtime error.
3)
#include <stdio.h>
void main(){
int c; c=5; printf("%d",c); }
The above code runs fine. What is the possible reason?
First,
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.
C 2011 Online Draft, §5.1.2.2.1 Program Startup
Unless your compiler documentation specifically lists it as a valid signature, using void main() leads to undefined behavior, which may be where your runtime errors are coming from.
Secondly, the current C standard does not require that main contain any executable statements.
I am writing a c program with void main function in code blocks.
I just write return with no value.
The program is as below:
#include<stdio.h>
void main (void)
{
printf ("ali tariq\n");
return;
}
However, in the console window the program returns the value 16 in the console window. "Process returned 16"
I want to know why it is returning this value?
How can i utilize this value in windows using codeblocks?
Thanks
In (hosted) C the main function must return an int (C11§5.1.2.2.1[1]). By declaring it with a return type of void, and not specifying any return value you invoke undefined behaviour. This means the compiler is free to return anything and in your case it turns out to be 16.
You are not free to declare the return type of main as you wish. Why?
BECAUSE YOU DIDN'T WRITE THE CODE CALLING main(). Sorry 'bout the shouting, but someone else wrote that code and placed it in crt0.o or so. Your main() is linked against that code and it can't just return what it wants because that code expects an int. Always. It's already written and compiled. You understand this subtle point?
Because the C Standard says so. See other answer by Kninnug for Chapter and Verse.
In other words, your code invokes undefined behavior and it should be no surprise to find a garbage value where no value was provided.
So you expected a warning from the compiler? The better ones indeed will catch this with the right options. E.g. gcc and clang support -Wmain-return-type.
You should not use void main(), use int main() instead.
The program has undefined behavior. First of all according to the C Standard main without parameters shall be declared like
int main( void )
You declared the function as having return type void. In this case the process that starts the program can not get a valid return code of the program.
Just because a function is declared as void doesn't mean it won't return anything. On the x86, for example, a lot of calling conventions specify that the value in the register EAX after a function call is the return value of the function. So, if you have a C function that is declared void but the machine code for the function changes the value of EAX, that will get treated as the return value for the function.
EVERY "normal" program that terminate execution WITHOUT errors, must return ZERO.
So, your program must be:
#include<stdio.h>
int main (int argc, char *argv[]) // your program may have command line parameters
{
printf ("ali tariq\n");
return 0; // Program terminate with NO ERRORS
}
However there are cases when one program may terminate WITH errors.
Let's suppose this:
#include<stdio.h>
void main (int argc, char *argv[])
{
// program to make a division between two numbers
double a, b, res;
a = b = res = 0.0;
printf ("Enter 1st number: ");
scanf ("%lf", &a);
printf ("Enter 2nd number: ");
scanf ("%lf", &b);
if (b == 0) return 1; // division by '0' then return ERROR (any number != 0)
printf ("%f / %f = %f", a, b, a/b);
return 0; // NO ERROR
}
Now you may ask: «But where is the return value evaluated?
Answer: «By the Operating System.»
One batch file may run your program and read the integer YOU returned in the environment variable 'ERRORLEVEL'
#include <stdio.h>
int read_next_line()
{
int ch;
int flag=0;
ch=getchar();
while(ch!= EOF && ch!='\n') {
ch=getchar();
flag=1;
}
return flag || (ch=='\n');
}
int read_all_lines()
{
int linecount=0;
int isvalid;
while(!feof(stdin)) {
isvalid=read_next_line();
linecount=linecount + isvalid;
}
return linecount;
}
main {
read_all_lines();
}
The above code gives an error saying main does not have a type.
How to solve the problem ?
main is a function that returns a value like other functions. It is up to you if it returns nothing void main(void){ } or an int value, 0 is returned in POSIX systems if no error encountered. More sophisticated but readable is to put exit(EXIT_SUCCESS);.
int main(void){
...
}
The proper prototype in most environments is:
int main(int argc, char *argv[])
This means:
main() is a function that returns an int.
It has one argument called argc that is the number of command-line arguments.
It has one argument called argv that is an array of those arguments.
It should be int main() instead of simply main
Since C98 I think, C disallows to declare a function without using the return type for the result anymore. You have to declare main as
int main ()
{
...
}
This is the minimum requirement to make your code compilable. In previous releases of the C language, it was allowed to declare a function like you have done. Implicitly, the compiler assumed it to be an int function without any complaint. But, as for sure you have your compiler configured to compile post C98 or later code, it complaints with an error. Previous versions of actual compilers issue normally a warning, telling you main will be assumed to be an int function, and this is to be able to compile old pre-ANSI code.
By the way, next time, don't limit yourself to explain what you have coded. Cut and paste your actual code here, and also the exact error you got from the compiler (probably, it was only a warning, but you didn't include it, so we'll never know) Probably the mistake is not where you think of, and that way saves us time and you the need of receiving this complaint.