• C

single line expression comparison

I need a single expression in C  that does not use ?: whose value is -1,0,or +1 depending on whether i is less than, equal to, or greater than j.


Thanks
jjackson2004Asked:
Who is Participating?
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
result = (i > j) - (i < j);
0
 
jjackson2004Author Commented:
Thanks.   Would you mind explaining why this works?  If i>j is false, does this become 0 and if i<j is true, the 0-1 = -1.  If i is greater than j, then it is 1-0 and if both are false, then it is 0-0?

0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Yep, that's the idea.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.