in c the return value for main()

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sanjay123456
    New Member
    • Sep 2006
    • 125

    in c the return value for main()

    Dear Friend ,

    in c the return value for main() is optional why in c++ the main() must return value ?

    sanjay
  • willakawill
    Top Contributor
    • Oct 2006
    • 1646

    #2
    Originally posted by sanjay123456
    Dear Friend ,

    in c the return value for main() is optional why in c++ the main() must return value ?

    sanjay
    Hi sanjay
    C and C++ have different ANSI standards. Both require an int to be returned from main() but the compiler will allow void in C. The runtime environment still expects an int to be returned so anything could happen. In C++ the compiler will fail if anything other than an int is declared. This is part of C++ standards.

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      In both C and C++ main MUST return int. Not doing so invokes undefined behaviour (it just happens that in many cases that the undefined behaviour is everything works as expected which is a possible outcome of undefined behaviour).

      Undefined behaviour is a bad thing to invoke as anything could happen, the compiler is at liberty to create any code it chooses.

      As willakawill states C++ compilers are just better at detecting this error but it does not mean that it is not an error in C.

      main should be declared as

      int main(int argc, char **argp);


      In C99 and C++ you also have the option of declaring it as

      int main(void);

      but not in C89/C90

      Comment

      Working...