Reputation: 997
My goal : Enter two integers and sum all the integers from the small number to the big number.
#include <iostream>
int main() {
int v1, v2;
std::cout << "Enter two integers: " << std::endl;
std::cin >> v1 >> v2;
int big, small;
big = v1 > v2 ? v1, small = v2 : v2, small = v1;
int sum = 0;
for (int i = small; i <= big; i++)
sum += i;
std::cout << "The sum is " << sum << std::endl;
getchar();
getchar();
return 0;
}
Instead of using if statement, I want to test ternary condition operator.
When v1 is smaller than or equals v2, like
Enter two integers:
1
5
The sum is 15
The result works fine.
But when v1 > v2, the result is wrong.
Enter two integers:
5
1
The sum is 0
I can't think of why. Can someone explain , please?
Upvotes: 1
Views: 240
Reputation: 2275
big = v1 > v2 ? v1, small = v2 : v2, small = v1;
This doesn't do what you expect.
When using the comma operator ,
to separate a number of expressions, the resulting expression gets the value of the last of those expressions. So in your case, if v1 > v2
, big
is assigned the value of:
v1, small = v2
which is the value of small = v2
, which becomes v2
instead of v1
as you intended. So you end up assigning both numbers the same value when v1 > v2
!
You could use separate statements:
big = v1 > v2 ? v1 : v2;
small = v1 < v2 ? v1 : v2;
Upvotes: 2
Reputation: 16876
You need to swap the terms on each side of the comma operator because big
will be assigned the last one on the list. You also need to add parentheses in order to make it evaluate correctly:
big = (v1 > v2) ? (small = v2, v1) : (small = v1, v2);
See the explanation here:
In a comma expression
E1, E2
, the expressionE1
is evaluated, its result is discarded [...] The type, value, and value category of the result of the comma expression are exactly the type, value, and value category of the second operand,E2
Also, if you want it to be short and readable, you could consider this instead:
std::cin >> big >> small;
if (small > big)
std::swap(big, small);
Upvotes: 6