Which is better: -float(x) or float(-x) , where x is of type unsigned short ?

  • better for what? - Grundy
  • one
    1 is better. To do - to the unsigned one is somehow ugly, and there is no difference godbolt.org/g/IQG8VZ - pavel
  • @ user227660 As they say, there are no comrades to taste and color. :) - Vlad from Moscow

2 answers 2

For unsigned short does not matter (for sizeof(short) < sizeof(int) ), because Your float(-x) expression will first lead x to int , make it negative, and then lead to float - no problem.

The problems will begin if you have an unsigned int and “higher” type - in this case the variant with float(-x) will not give what you expect, since first, the new x will be calculated based on the formula 2^n - x , and then it will be converted to float ; where n is the width of the original type (in our case, int ).

Therefore, in order to avoid problems, it is better to always adhere to the first option ( -float(x) ), as the safest and best reflecting the intention.

  • well, or if you have a 16-bit compiler) for example borland C ... - pavel

Perhaps the first is better conveys the intention of the programmer. Formally, the application of minus to unsigned does not look very nice ...

  • by the way is it just ugly or ub? - pavel
  • @pavel I won’t say it, but float (unfigned) shouldn’t be exactly :) - Harry
  • one
    if sizeof (int) == sizeof (short) it will be bad ideone.com/VMtrpr - pavel
  • @pavel There is no UB here. - Vlad from Moscow
  • @VladfromMoscow simply if you do this with the results, then the results are different. So he asked why - pavel