warning at function calc closing brace

#include <iostream>

using namespace std;

double calc(double operand1, double operand2, char oper)
{
if (oper == '*')
return operand1 * operand2;
else if (oper == '/')
return operand1 / operand2;
else if (oper == '+')
return operand1 + operand2;
else if (oper == '-')
return operand1 - operand2;
}

int main()
{
double op1, op2;
char op;
do{
cout << "Enter expression: ";
cin >> op1 >> op >> op2;
cout << "Result: " << calc(op1, op2, op) << endl;
}while(true);

return 0;
}

I don't understand, the program works fine but I get a warning at the calc function closing brace.

The warning is: Warning: control reaches end of non-void function [-Wreturn-type] }

Can anyone tell me why?
Last edited on
If the oper is not one of * / + -, calc will not return. So not all paths return a value in your calc function.

One option is to change the final "else if (...)" into just "else", and sanitize the input beforehand.
Another option is to throw an exception if control reaches past the final else-if. Exceptions would only be if you really don't expect it to happen (exceptions should only be for exceptional cases, and not routine logic).

Or some other type of error-handling (e.g. returning a bool to indicate success, and pass the result via an out parameter reference.).
Last edited on
Thanks for the advice.
That worked. I added a return statement with a -1 return value to the end
of the function and that fixed it.
it was not broken, honestly, so long as the operator was in range.
now, being nefarious, I put in 3,4, and minus, and the answer is -1.
how do you know if that was your default/error result, or legit?

I would check the inputs to ensure the operators are valid. You can leave the return in place to silence the warning, and maybe put an assert if it gets there as that should be unpossible now.
Topic archived. No new replies allowed.