我有以下代码:
// ---- 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);
}
专线pt.x += dx;
产生警告
conversion from 'int' to 'int16_t', possible loss of data
我该怎么办?
- 禁用这些行的警告
- 将警告源移至接口(interface):make
dx
和dy
int16_t,所以谁会用move_point
函数将处理这个问题。 - 刚投
dx
和dy
到 int16_t。 - 添加
assert(dx <= 0x7FFF && dx >= -0x8000 && "too large 'dx' value")
并希望它会在我运行调试版本时命中。
最佳答案
您应该将 dx 和 dy 设置为 int16_t,如果您强制转换它们,您只是将其隐藏,使用您的代码的人将不会看到这些警告并且不会意识到问题所在。因此,让另一方的人处理警告,至少他们当时对功能有把握。
关于c++ - 转换具有不同容量的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4566210/