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

  • Context: C/C++ 
  • Thread starter Thread starter firekid123
  • Start date Start date
  • Tags Tags
    Error Function
Click For Summary

Discussion Overview

The discussion revolves around how to print error messages in the main function based on the return value of another function in C/C++. It includes aspects of error handling and function return values.

Discussion Character

  • Technical explanation
  • Conceptual clarification
  • Homework-related

Main Points Raised

  • One participant describes a scenario where they want to print an error message using cerr in the main function when an error occurs in another function.
  • Another participant suggests checking the return value of the function in an if statement to determine if there was an error.
  • A later reply acknowledges that the suggested approach worked for the original poster.
  • Another participant proposes using exception handling with throw and catch statements as a more general solution to avoid checking return values for every function call.

Areas of Agreement / Disagreement

Participants generally agree on the need to check return values for error handling, but there are multiple approaches suggested, including both return value checks and exception handling.

Contextual Notes

The discussion does not resolve the effectiveness or appropriateness of the different error handling methods proposed.

firekid123
Messages
8
Reaction score
0
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?
 
Technology news on Phys.org
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:
if (/*error value*/ == function(/*parameters*/)) {
  // ...
}
 
Thanks, that worked.
 
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.
 

Similar threads

  • · Replies 6 ·
Replies
6
Views
12K
  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 39 ·
2
Replies
39
Views
5K
  • · Replies 11 ·
Replies
11
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 23 ·
Replies
23
Views
3K
Replies
1
Views
2K
  • · Replies 70 ·
3
Replies
70
Views
5K
Replies
20
Views
2K
  • · Replies 5 ·
Replies
5
Views
3K