Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C/C++ How do I get main to print out an error from a function?

  1. Oct 18, 2011 #1
    I'm having trouble with printing out an error with cerr in the main function when there's an error in another function.


    Example:

    int main (){
    //body
    //statements

    function (//parameters);
    cerr<<"there's a problem"<<endl;
    }
    int function (//parameters){
    if a < b
    return -1;
    else
    return 0;
    }

    How would I get main to print out the error of the function?
     
  2. jcsd
  3. Oct 18, 2011 #2

    diazona

    User Avatar
    Homework Helper

    If the return value of the function is what indicates that there was an error, you need to check the return value in an if statement.
    Code (Text):
    if (/*error value*/ == function(/*parameters*/)) {
      // ...
    }
     
  4. Oct 18, 2011 #3
    Thanks, that worked.
     
  5. Oct 18, 2011 #4

    AlephZero

    User Avatar
    Science Advisor
    Homework Helper

    For a more general way where you don't have to remember to check the return value from every function call, find out about exception handling and the throw and catch statements.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook