What is the correct way to write the main function in C?
So?:
main(){
}
Or this way?:
int main(){
return 0;
}
Because I don't really understand what is the difference between the two.
What is the correct way to write the main function in C?
So?:
main(){
}
Or this way?:
int main(){
return 0;
}
Because I don't really understand what is the difference between the two.
The function
main
can only be written in two ways in c :Any other way is not standard.
TLDRs;
First of all, let's remember how is the definition of a function in
c
, that at the end of the day,main
it is nothing more than the main functionTo see an example we will run this small program
If we run the program we can see that it will print 8. Since we have declared that the function
testear
is going to return aint
.Functions
int
, if they are not assigned a return value, returndefault
0. Let 's seeIn this example we see that even if we don't pass any to it, it
return
prints0
. Since, as mentioned, it is the default value for functions inreturn int
.Now what happens if we don't define the type, that is, as follows.
We can see that this returns a
0
anyway, since the default return variable type is aint
. however we can notice here the followingwarning
This is because it advises against not returning a return variable, in
c
causes only a warning, and inc++
causes an error.Now what if we don't want to return a return variable
We can define
void
that it means that the function does not return any value. In fact if we try to do the following.#include <stdio.h> void test() { int variable = 8; printf("%i", test()); }
We can notice the error, since it
testear
doesn't return any value.ABSTRACT
In
c
is usedint main(){return 0;}
and the return number means whether your program executed properly, leaving 0 asejecución correcta
or returning another numeric value indicating that the execution failed at something.main(){...}
returns the same asint main(){return 0;}
given that if no return type is defined in a function the return value type isint
bydefault
and the value bydefault
for functionsint
when not explicitly declared is0
. However it is discouraged not to define return value type in a function. You can usevoid main(){...}
it if you don't want to declare a return variable in your functionmain
, however also in several places like in this article they mention that according to the ANSI standardC
it shouldn't be usedvoid main(){...}
so the best option is to always useint main(){}