Results 1 to 5 of 5

Thread: int/void main

  1. #1
    Join Date
    Sep 2011
    Location
    Wandering
    Beans
    75
    Distro
    Ubuntu 10.04 Lucid Lynx

    int/void main

    Is it better in c/c++ to state the main function as int main or as void main and why?

  2. #2
    Join Date
    Jul 2011
    Beans
    5

    Re: int/void main

    The C++ standard says int is the only acceptable return type for the main function in C++.

  3. #3
    Join Date
    Jul 2009
    Beans
    109
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: int/void main

    Quote Originally Posted by dep0 View Post
    Is it better in c/c++ to state the main function as int main or as void main and why?
    You probably should always use:

    Code:
    int main ( int argc, char** argv){
        int errorcode;
        //do something
        if (/*succesfull*/){
            return 0;
        }
        else {
            return errorcode;
        }
    }
    As I a kind of pseudo coded a program can return it's exit status. So if some other program executes the above it can see if it returned 0. This tells the program did it's job as intended.

    for example say you rewrite cd (change directory) program. But you forgot to return it's exit status another programmer might use your program.

    Code:
    cd important_files
    cd temporary_files
    rm * -rf
    And maybe the pseudo code above could cd to important_files but not to the temporary files, then rm -rf * would erase all files in the important_file directory.

    but if you provide a exit code from your program the program can see if cd worked like it should

    Code:
    if ( cd important_files != 0 ){
             exit();
    }
    if ( cd temporary_file != 0 ){
             exit();
    }
    rm -rf *
    so in this example another user could check if your cd program exited with 0 indicating that no error occured. And now his/her program only runs the rm * -rf directory if his/her program was able to use cd two times succesfully.

    So in short you should report the exit status from a program to give the environment of the program the information if a program has run properly or not.

    cheers,
    Windows DOS not compute...

  4. #4
    Join Date
    Sep 2011
    Location
    Wandering
    Beans
    75
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: int/void main

    Thank you both for the replies.

  5. #5
    Join Date
    May 2007
    Location
    Leeds, UK
    Beans
    1,675
    Distro
    Ubuntu

    Re: int/void main

    Quote Originally Posted by AnotherTest View Post
    The C++ standard says int is the only acceptable return type for the main function in C++.
    And here are the references in Stroustrup's C++ Style and Technique FAQ:

    http://www2.research.att.com/~bs/bs_faq2.html#void-main

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •