Convert integers with different capacities

I have the following code:

// ---- third party library code ----
struct Point { int16_t x, y; };
void third_party_library__getPoint(Point*);
void third_party_library__setPoint(const Point*);

// ---- my library code ----
void move_point(int dx, int dy)
{
    Point pt;
    third_party_library__getPoint(&pt);
    pt.x += dx;
    pt.y += dy;
    third_party_library__setPoint(&pt);
}

The line pt.x += dx;gives a warning
conversion from 'int' to 'int16_t', possible loss of data

What should I do?

  • disable warning for these lines
  • move the warning source to the interface: make dxand dyint16_t, so whoever uses the function move_pointwill deal with this problem.
  • just type dxand dyin int16_t.
  • add assert(dx <= 0x7FFF && dx >= -0x8000 && "too large 'dx' value")and hope that it will hit when I run the debug version.
+3
source share
6 answers

For me there are three related, but different points:

and. Overflow deal

, : . int16_t , +=, , (, , , ).

.

(3) - , , . , . , "" , .

.

(A), , , .


(1) (3), , , . "", "" "".

(2) . , .

(4) Inform, Deal Avoid.


? , - , .. . , - , , / .. , , .

+2

dx dy int16_t, , , , , . , , .

+4

, , ( 15, ), "casting".

, , :

pt.x += int16_t(dx);

, - , , , 16-.

+1

int16_t, int16_t.

+1

4, (, ).

  • , (, )

  • : dx dy int16_t, , move_point,

    , .

  • dx dy int16_t.

    , ().

    BTW pt.x += int16_t(dx) "" ; , pt.x = int16_t(pt.x + dx) ( - )

  • add assert (dx <= 0x7FFF & dx >= -0x8000 && "too large" dx 'value ") , , .

    - , , ( , , , , , ). ( ):

    assert(int16_t(dx) == dx);
    
+1

add assert (dx <= 0x7FFF & dx> = -0x8000 && "dx value is too big") and hope that it will hit when I run the debug version.

Well, obviously, you should handle the “potential” error (I would call it a complete error, by the way).

To accept the warning (knowing that only 16-bit numbers will be passed to your function), you can add a cast that expresses what you are doing, throwing out the 16 high-order bits anyway.

All this said, assuming you have a 32 or 64-bit platform.

0
source

Source: https://habr.com/ru/post/1782837/


All Articles