I'm writing a program for homework, it's teaching us to use reference parameters.
The main function prompts for 2 ints from the user then calls another function that gets the sum, difference, and product. It then checks if the second int is a zero and if it is not it gets the quotient and remainder. Once the function is done the main function displays the results and displays an error message on the quotient/remainder part if the second integer is 0. The problem I'm having is what value do I use for quotient that main can check and know that it should display the error message instead of the value? Since any integer value I use could cause a conflict with a real quotient or remainder. Thanks.
If you're returning a float or double, you could use http://cplusplus.com/reference/std/limits/numeric_limits/ to check if it is NaN or Infinity (I don't remember which one division by 0 causes).
Though a simpler solution would be to return a bool divisionByZeroErrorFlag.
The thing is he wants use to use reference parameters so the function has a void return datatype. So the only thing the function is doing is referencing the arguments from the main function and changing those values.
> he wants use to use reference parameters so the function has a void return datatype.
Check if the second integer is zero in main() and display an error message if it is.
1 2
if( second_integer == 0 ) { /* display error message */ }
else { /* print out quotient and remainder returned by the function */ }
Pass an extra (output) parameter by reference to indicate an error
1 2 3 4 5
// if second == 0, divide_by_zero_error is set to true and quotient and remainder are not set
// if second != 0, divide_by_zero_error is set to false and quotient and remainder are set
void foo( int first, int second,
int& sum, int& difference, int& product,
int& quotient, int& remainder, bool& divide_by_zero_error ) ;
Put an impossible value in an output parameter to indicate an error
1 2 3 4 5
// if second == 0, remainder is set to std::numeric_limits<int>::max()
// if second != 0, remainder is set to first%second
void bar( int first, int second,
int& sum, int& difference, int& product,
int& quotient, int& remainder ) ;
Throw an exception? No, I suppose you haven't encountered throw/try/catch yet.
And do not forget to tell your professor that the way he has asked you to write the function is truly horrible.