Why is an integer being handled as a boolean?
I have set up a function that is meant to return a boolean, and the input type is int to allow for invalid numbers without crashing.
1 2 3 4 5 6 7 8 9 10 11 12
|
bool getDone() {
int doneIn = 0;
cout << "Do you wish to convert another value?\n\n1: Yes\t2: No\n\nSelection: ";
cin >> doneIn;
if (0<doneIn<3) {
return doneIn-1;
}
else {
cout << "\nInvalid selection.";
return 1;
}
}
| |
The trouble is that the expression
0<doneIn<3 appears to throw the following error, even though the variable
doneIn has been declared as an int:
warning: result of comparison of constant 3 with expression of type 'bool' is always true
This is evaluated as (0 < doneIn) < 3.
which is either evaluated as (true) < 3, or (false) < 3, (Which will always be true in this situation).
You want to do: if (0 < doneIn && doneIn < 3)
Last edited on
Thank you :)
I can see how it would parse it as you described, and utilizing your suggestion has resolved the issue.
Topic archived. No new replies allowed.