开发者

An interview question on conditional operator

开发者 https://www.devze.com 2022-12-23 01:03 出处:网络
I recently encountered with this question: How to reduce this expression: s>73?61:60;. The hint given was that Instead of using co开发者_开发百科nditional operator we could use a simple comparison wh

I recently encountered with this question: How to reduce this expression: s>73?61:60;.

The hint given was that Instead of using co开发者_开发百科nditional operator we could use a simple comparison which will work fine.

I am not sure but I think it is possible with some GCC extension,although I am unable to figure it out myself.

EDIT:The whole expression is this : s-=s>73?61:60


Just like the other answers:

s -= (s > 73) + 60;

This expression works because the spec defines the results of the relational operators. Section 6.5.8 paragraph 6:

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false. The result has type int.


How to reduce this expression: s-=s>73?61:60;

How about:

typedef int Price;
Price getPriceAfterRebate(const Price priceBeforeRebate)
{
  const Price normalRebate = 60;
  const Price superRebate = 61;

  const Price superRebateThreshold = 73;

  Price returnValue = priceBeforeRebate;
  if (priceBeforeRebate > superRebateThreshold)
  {
    returnValue -= superRebate;
  }
  else
  {
    returnValue -= normalRebate;
  }
  return returnValue;
}

Tada! An ugly piece of unmaintainable code is reduced to a readable and maintainable block of code.


This is such an ugly piece of code that I can't beleive I wrote it, but I think it fulfills the requirement:

My answer to the original question which was s>5?6:9:

9 - (((int)(s > 5)) * 3)

Rewritten for the updated question:

61 - (int)(s > 73)


Maybe this?

60 + !!(s > 73)

The double-bang maps non-zero values to 1 and zero to zero.


What is the value of (s>5)? Could you do some arithmetic with that?

Without the hint, I would say this was a bad "gotcha" interview question that requires a particular a-ha insight that's not correlated with ability. With the hint, it's... nice, but dim.


If we assume that True = 1 and False = 0, then doesn't this work:

s-= (60 + (s > 73))


It can be thought of as s -= (s > 73) + 60 as > is a relational operator and it will return 1 or 0 depending on result of expression s > 73 ,As the return value is int so it will work fine

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号