I am just a beginner today and trying to learn desktop programming with C . And I am confused that why doesnt this work:
The code:
int math(int opt, int x, int y){
switch(opt){
case 1:
return x y;
break;
case 2:
return x - y;
break;
case 3:
return x * y;
break;
case 4:
return x / y;
break;
default:
break;
}
}
The use:
cout << to_string(math(1,1,2)));
The error:
main.cpp: In function ‘int math(int, int, int)’:
main.cpp:38:1: warning: control reaches end of non-void function [-Wreturn-type]
38 | }
| ^
Thank you all, as I understand:
- break; after return is extra because will be never executed
- need to return something in all cases(i.e. if opt is bigger than 5)
So this works now:
int math(int opt, int x, int y){
switch(opt){
case 1:
return x y;
case 2:
return x - y;
case 3:
return x * y;
case 4:
return x / y;
default:
return 0;
}
}
CodePudding user response:
The problem is, if you pass "invalid" opt
value, default
case gets selected, and your function returns nothing. So one solution would be to decide what to return if you pass invalid opt
.
You should fix your problem like this:
enum class Opt { PLUS, MINUS, TIMES, DIVIDED };
int math(Opt opt, int x, int y) {
switch(opt){
case Opt::PLUS:
return x y;
case Opt::MINUS:
return x - y;
case Opt::TIMES:
return x * y;
case Opt::DIVIDED:
return x / y;
}
// it is important to not have default: case
// above because now compiler will issue warning,
// you add new values to Opt.
// below line should never be reached, so value doesn't matter,
// but it's needed to disable warning on some compilers.
return 0;
}
// test
int main() {
return math(Opt::PLUS, 1, 2); // exit code 3
}
Using enum class
has the benefit, that if you want to shoot yourself into foot by passing random integer as opt
, you have use an explicit cast to convert the integer into an enum class value.
CodePudding user response:
A function that has any return type other than void
needs to reach a return
statement with the correct value type specified.
A function is built like this: returnType name(type parameterName, ...){}
If the return type is (as in your case) an int
, the path of execution must reach a return foo;
statement, where foo
is, or convertible to, an int
.
int math(int opt, int x, int y){
switch(opt){
case 1:
return x y;
case 2:
return x - y;
case 3:
return x * y;
case 4:
return x / y;
default:
throw std::invalid_argument("math parameter opt out of range!");
}
}
Also, any code after reaching a return
is not executed, so the break;
statements are extraneous.