Problem with ternary operator

0

I'm having trouble with the ternary operator. I want to use it to make the code more elegant because it is a simple thing. But it's like it does not work because it does not update the variable. The following example depicts 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? For the result of the variable k is shown as 0.

    
asked by anonymous 12.01.2018 / 15:41

2 answers

6

This expression will not do what you want:

k= (i<5)? k++:k;

This means the following:

Se i < 5, então:
    Avalia o k (que é zero).
    Incrementa o k, que será um.
    Atribui o valor avaliado ao k, ou seja, zero.
Senão
   Atribui k ao próprio k (não faz nada).

What you wanted is just that:

if (i < 5) k++;

There's no point in forcing the use of the ternary operator where it does not work. The ternary operator is very useful but it is not silver bullet. It is not just because the hammer is a sensational tool that it should be used to change a lamp.

    
12.01.2018 / 15:49
2

Or if you want to use the same conditional operator, even though the performance may be even worse:

k += i < 5 ? 1 : 0;

Or

k += i > 4 ? 5 : i; //ver comentário do Bacco acima

Or with probably better performance and less susceptible to bug of the processor :

k += !((4 + (~i + 1)) & 0x80000000);

This may not work in certain situations, so it is not a generic solution for any case.

#include <iostream>
using namespace std;

int main() {
    int k = 0;
    for (int i = 0; i < 10; i++) {
        k += !((4 + (~i + 1)) & 0x80000000);
    }
    cout << k << endl;
}

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

Or

k += !(i / 5); //ver comentário do Victor Stafuza abaixo

Only testing, but is likely to be more expensive, splitting is a tricky operation for the processor. It will be either faster or faster if the compiler knows how to optimize well (it's common to try to avoid splitting).

    
12.01.2018 / 16:14