c - Return type of main function -
possible duplicate:
what should main() return in c/c++?
difference between void main , int main?
i have been using main method in c
void main(){ // code }
and works pretty me. know other int
return type:
int main(void) int main() int main(int argc, char *argv[])
but have not been able find resource says can use void
return type. every book suggests return type must int
or else omitted. why void main()
work?
is dependent on version of c using? or work because use c++ ide? please reply specific c , not c++.
only book authors seem privy place return type of void
main()
allowed. c++ standard forbids completely.
the c standard says standard forms are:
int main(void) { ... }
and
int main(int argc, char **argv) { ... }
allowing alternative equivalent forms of declaration argument types (and names discretionary, of course, since they're local variables function).
the c standard make small provision 'in other implementation defined manner'. iso/iec 9899:2011 standard says:
5.1.2.2.3 program termination
if return type of
main
function type compatibleint
, return initial callmain
function equivalent callingexit
function value returnedmain
function argument;11) reaching}
terminates main function returns value of 0. if return type not compatibleint
, termination status returned host environment unspecified.11) in accordance 6.2.4, lifetimes of objects automatic storage duration declared in main have ended in former case, not have in latter.
this allows non-int
returns, makes clear not specified. so, void
might allowed return type of main()
implementation, can find documentation.
(although i'm quoting c2011 standard, same words in c99, , believe c89 though text @ office , i'm not.)
incidentally, appendix j of standard mentions:
j.5 common extensions
the following extensions used in many systems, not portable implementations. inclusion of extension may cause strictly conforming program become invalid renders implementation nonconforming. examples of such extensions new keywords, library functions declared in standard headers, or predefined macros names not begin underscore.
j.5.1 environment arguments
in hosted environment,
main
function receives third argument,char *envp[]
, points null-terminated array of pointerschar
, each of points string provides information environment execution of program (5.1.2.2.1).
why void main()
work?
the question observes void main()
works. 'works' because compiler best generate code programs. compilers such gcc warn non-standard forms main()
, process them. linker isn't worried return type; needs symbol main
(or possibly _main
, depending on system) , when finds it, links executable. start-up code assumes main
has been defined in standard manner. if main()
returns startup code, collects returned value if function returned int
, value garbage. so, sort of seems work long don't exit status of program.
Comments
Post a Comment