这是不可避免的有符号和无符号整数比较吗? [英] Is this an unavoidable signed and unsigned integer comparison?
问题描述
可能不是,但我不能想到一个很好的解决方案。我不是C ++的专家。
Probably not, but I can't think of a good solution. I'm no expert in C++ yet.
最近我把很多 int
转换为 unsigned int
。基本上不应该为负的一切都是无符号的。这移除了MinGW的许多警告:
Recently I've converted a lot of int
s to unsigned int
s in a project. Basically everything that should never be negative is made unsigned. This removed a lot of these warnings by MinGW:
警告:有符号和无符号整数表达式之间的比较[-Wsign-compare] >
warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
我喜欢它。它使程序更健壮,代码更具描述性。然而,有一个地方,他们仍然发生。它看起来像这样:
I love it. It makes the program more robust and the code more descriptive. However, there is one place where they still occur. It looks like this:
unsigned int subroutine_point_size = settings->get<unsigned int>("subroutine_point_size");
...
for(int dx = -subroutine_point_size;dx <= subroutine_point_size;dx++) //Fill pixels in the point's radius.
{
for(int dy = -subroutine_point_size;dy <= subroutine_point_size;dy++)
{
//Do something with dx and dy here.
}
}
在这种情况下,我不能使 dx
和 dy
无符号。
In this case I can't make dx
and dy
unsigned. They start out negative and depend on comparing which is lesser or greater.
我不喜欢使用 subroutine_point_size
签署,虽然这是较小的邪恶。它指示在传递图像时内核的大小,并且内核大小不能为负(对于用户来说,将内核大小设置为大于100的内容大小可能是不明智的,但是设置文件允许数字达到2 ^ 32 - 1)。
I don't like to make subroutine_point_size
signed either, though this is the lesser evil. It indicates a size of a kernel in a pass over an image, and the kernel size can't be negative (it's probably unwise for a user ever to set this kernel size to anything more than 100 but the settings file allows for numbers up to 2^32 - 1).
所以似乎没有办法转换任何变量来解决这个问题。有没有办法摆脱这个警告,并解决这个整洁?
So it seems there is no way to cast any of the variables to fix this. Is there a way to get rid of this warning and solve this neatly?
我们使用C ++ 11,使用GCC编译Windows,Mac和各种Unix发行版。
We're using C++11, compiling with GCC for Windows, Mac and various Unix distributions.
推荐答案
将变量投射到 long int
或 long long int
类型同时给出unsigned int(0..2 ^ 32-1)的范围和符号。
Cast the variables to a long int
or long long int
type giving at the same time the range of unsigned int (0..2^32-1) and sign.
这篇关于这是不可避免的有符号和无符号整数比较吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!