historystamp historystamp - 3 months ago 7
C Question

Confusing 'if' statement

What is the statement below doing anyway?

It's confusing to me. I am surprised that C allows you to use the conditional operator in an

if
statement. Is there a better way?

I find the conditional operator in an
if
statement too confusing. I could try to use the && and || operators, but I'm afraid I might make a mistake.

How can the statement below be rewritten to be of a simpler form?

if ( (offset < 0) ?
( input->binData.bounds.lo >= (unsigned long)(-offset) ) :
( input->binData.bounds.hi < (unsigned long)(-offset) ) )


I found this line of C code in the BitHoist open source package.

Answer

You can AND the ternary condition (offset < 0) and its opposite (offset >= 0) with each resolution of the ternary operator:

if ( ((offset < 0) && ( input->binData.bounds.lo >= (unsigned long)(-offset) )) ||
     ((offset >= 0) && ( input->binData.bounds.hi <  (unsigned long)(-offset) )) ) {
Comments