Is this basically a duplicate ternary operator ?: vs if ... else
For most compilers, the efficiency will be the same, and the compiler optimizes the three-dimensional operator in the same way as it optimizes the if / else operator. However, I prefer statements if they make the code much easier to read with a quick glance.
To answer other questions. I'm not sure what you mean, if you just set a single integer or variable to 0, then there is no faster way than setting it to zero, as you have above.
If you have an array of variables, you can use memset(ptr, 0, size*sizeof(TYPE)) , which would probably be the fastest if you had an array of variables that you wanted to set to zero. Or maybe std :: fill_n
I'm not sure what you are trying to achieve using the logic above, but that seems a little strange. There are ways to streamline the code, which will mean that you probably won't need the conditional condition at all, but it's hard to say for your situation without seeing a bit more code.
Honestly, if you do not perform this operation billions of times, this is probably a very preliminary optimization, and you should focus on readability.
source share