Reputation: 2227
So I have to do a simple program for my college class, which would include a structure fraction
with numerator and denominator as ints
and a function is_correct()
checking two conditions: is denominator!=0
and is nominator<
denominator. If two of them are true, then I should return true
, otherwise false
. I'm obligated to use ?:
operator. So here's my code:
struct fraction {int n,d;
bool is_correct(){
d!=0?(return n<d?true:false):return false;
};
};
I mean, I guess I could use one if
with condition d!=0
, but I have to use only ?:
, and g++
gives me that: expected primary-expression before 'return'
Upvotes: 2
Views: 112
Reputation: 62052
If two of them are true, then I should return true, otherwise false
This is a pretty standard truth table, right?
| T | F
---+---+---
T | T | F
---+---+---
F | F | F
And I know an operator that has an identical truth table: &&
.
We don't need a ternary here at all. We can simply write:
return d != 0 && n < d;
An even more concise solution looks like this:
return d && n<d;
But I'll make the case that the first solution more clearly expresses the coder's intent, which is an important consideration.
Upvotes: 5
Reputation: 1209
struct fraction {
int n,d;
bool is_correct() {
return d != 0 ? (n < d ? true : false) : false;
};
};
Upvotes: 1
Reputation: 11706
Just move the return
outside of the condition (spacing added for clarity):
return d != 0 ? (n < d ? true : false) : false;
Upvotes: 3