In some compilers void main() works but actually return type of main() is int, how does this work?
Printable View
In some compilers void main() works but actually return type of main() is int, how does this work?
Actually in C, every function retuns integer defaulty.
But not every function must return integer.
we can change the return type.
Main is also an function, so we can change the return type.
[QUOTE=chpushpakumar;17338]Actually in C, every function retuns integer defaulty.
But not every function must return integer.
we can change the return type.
Main is also an function, so we can change the return type.[/QUOTE]
That is correct, but for that we need to change the prototype of the function as well and in case of main we can't do that, isn't it?
In C, every program execution starts from main and ends with main. So the first function executed in main it self. So no need to prototye main function, if we change the return type.
The summary as interpreted by me is something like this:-
1. ANSI / ISO standards for C and C++ languages does not support void main()
2. Compilers seem to allow this syntax, however with this syntax a random value is returned to the environment calling the C program.
3. This syntax can cause scripts to fail, in case they depend on the return value of a program.
4. This syntax can also cause stack corruption in some extreme cases
So points to be well remembered are -
1. definitely think whether the program is going to be executed by other programs / scripts etc - if so write int main() -
2. also if you worry about cross-compiler compatibility of the programs or compliance to standards - use int main()
3. Very simple rule of thumb - always use int main() except when there is some specific reason to use void main()
[QUOTE=pbchaudhari;17014]In some compilers void main() works but actually return type of main() is int, how does this work?[/QUOTE]
Default return data type of any function in Cpp is int ,it mean when you are not specify any datatype at that point compiler will set main() function with int as return datatype.(function type:no arg or with arg but with return value).but when you specify void as datatype at that point compiler will set with(function type:no arg or with arg but no retrun value).
It can be over loaded ,also final.