Is there any way to optimize the following line of C code (to avoid branching)?
if (i < -threshold || i > threshold) {
counter++;
}
All variables are 16-bit signed integers. An optimized version should be highly portable.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
How about the following:
Assuming the original code was valid, then this should work too, in a portable way. The standard says that relational operators (
<,>and so on) return anintequal to1on success, or0on failure.Update
To answer Sheen’s comment below, the following code:
results in the following disassembler on x86 using GCC, with no optimisations: