0
I have a problem with the ternary operator. I want to use it to make the code more elegant because it is simple. But it’s as if it doesn’t work because it doesn’t update the variable. The following example shows the problem:
#include <iostream>
using namespace std;
int main()
{
int k=0;
for(int i=0;i<10;i++){
k= (i<5)? k++:k;
}
cout << k << endl;
return 0;
}
What can it be? Because the result of the variable k
is shown as 0.
If you want to assign the value to
k
, why is using the operator++
, auto increment? Do you know how this operator works? In my view, writeif (i < 5) k++;
would be much more readable than the ternary operator.– Woss
As it is not possible to know the final goal, what was asked has infinite possibilities. Follow one more to the collection:
for(int i=0;i<10;i++) k = i > 4 ? 5 : i;
. Now, depending on the scenario, the most elegant would be this:cout << 5 << endl;
– Bacco
To fix it, just change it
k++
for++k
, but there are other ways to correct this assignmentk=( i<5 ? k++ : k );
. How aboutk=( i<5 ? k+1 : k );
? Ork+=int( i<5 );
? Ork+=( i<5 ? 1 : 0 );
?– RHER WOLF