This post demonstrates the difference between
Consider the following two definitions of
and
The above program compiles and runs fine, but the following program fails in compilation -
Please share your thoughts on this post in the comments section.
int main()
and int main(void)
in C/C++.Consider the following two definitions of
main()
-int main() { /* */ return 0; }
and
int main(void) { /* */ return 0; }
What is the difference?
In C++, there is no difference, both definitions are same.Both definitions work in C also, but the second definition with
void
is considered technically better as it clearly specifies that main can only be called without any parameter.
In C, if a function signature doesn't specify any argument, it means that the function can be called with any number of parameters or without any parameters.For example, try to compile and run following two C programs (remember to save your files as .c). Note the difference between two signatures of
fun()
.// Program 1 (Compiles and runs fine in C, but not in C++) void fun() { } int main(void) { fun(10, "GfG", "GQ"); return 0; }
The above program compiles and runs fine, but the following program fails in compilation -
// Program 2 (Fails in compilation in both C and C++) void fun(void) { } int main(void) { fun(10, "GfG", "GQ"); return 0; }
Unlike C, in C++; both of the above program fails in compilation. In C++, bothSo the difference is, in C,fun()
andfun(void)
are same.
int main()
can be called with any number of arguments, but int main(void)
can only be called without any argument. Although it doesn't make any difference most of the times, using int main(void)
is a recommended practice in C.
Try yourself -
//Question 1: #include <stdio.h> int main() { static int i = 5; if (--i){ printf("%d ", i); main(10); } } //Question 2: #include <stdio.h> #include <stdio.h> int main(void) { static int i = 5; if (--i){ printf("%d ", i); main(10); } }
Please share your thoughts on this post in the comments section.
It's worth noting that calling main is fine in C, but is ill-formed in C++
ReplyDelete// with the visual studio 2013,Compiles and runs fine in C
ReplyDeletevoid fun(void) { }
int main(void)
{
fun(10, "GfG", "GQ");
return 0;
}
Could you please check which compiler you are using? I am using GCC compiler (Code::Blocks IDE). Getting the error message : "too many arguments to function fun".
DeleteAnd in C++, return 0; is optional at the end of main().
ReplyDeleteYes. You are right. Thanks!!!
Delete