+=(relation) the meaning of code for selection process [duplicate]

counter += (a1<=x);

what this code statement says ?

it is used in a problem to get how many numbers is lower than or equal (x) variable,

this should be as comparison between a1 and a2 to get what is less than or equal variable x

  • 1

    This is the kind of code written by people who think they can outsmart current compilers. And no they can’t just write if (a1<x). Trust your compiler to generate optimized cod for you see : godbolt.org/z/KW4sehhjr

    – 

  • 2

    @PepijnKramer: Umm… Are you sure that link says what you think it says? They actually produced different output (which mildly surprises me, I’d assumed they’d produce the same thing), and there’s no obvious way to tell which is faster. It’s almost certainly contextual; if half the values lead to an increment, and half don’t, and the order is random, the counter += a1 <= x; code is likely to win (due to branch mispredictions in the if-based code). If 99% of the values, or long runs of the values, always test the same way, if (a1 <= x) ++counter; might win by a tiny bit.

    – 




  • 1

    Branch misprediction causes real problems in some code, and it is in fact fixed by rewriting it as branchless code.

    – 

  • Don’t write code like this.

    – 

  • @ShadowRanger Me bad, You’re absolutely right missed branch predictions are bad. Still if performance isn’t an issue I’d opt for the more readable version. (next step might be to add [[likely]],[[unlikely]] hints)

    – 




It feels like an unnecesssarily complicated way of saying:

if(a1 <= x) counter++;

If we are to believe that “true” defaults to “1” and “false” defaults to “0” when converting boolean to int.

Leave a Comment