有符号/无符号比较和 -Wall
我最近开始使用 -Wall 编译器开关来尝试提高代码质量。它(正确地)给出了关于这个小片段的警告...
int i;
for (i = start - 1; i >= 0; i--)
{
if (i >= number1.array.size())
{
one_value = 0;
}
因为 number1.array.size 是无符号的(它是 std::vector 上的 size 方法)。由于循环中的测试是 i >= 0,所以 i 必须被签名,否则不起作用。看来我有三个选择;避免使用 -Wall、忽略警告或引入辅助元素......
int i;
unsigned int j;
for (i = start - 1; i >= 0; i--)
{
j = i;
if (j >= number1.array.size())
{
one_value = 0;
}
这些似乎都不是特别理想的。您能提出任何替代方案,或者就这种情况下我应该做什么提出建议吗?
I have recently started using the -Wall compiler switch in an attempt to improve the quality of my code. It is giving (correctly) a warning about this little snippet...
int i;
for (i = start - 1; i >= 0; i--)
{
if (i >= number1.array.size())
{
one_value = 0;
}
because number1.array.size is unsigned (it's the size method on a std::vector). Since the test in the loop is i >= 0, i has to be signed or it doesn't work. It seems I have three choices; to refrain from using -Wall, to ignore the warning, or to introduce an ancillary element...
int i;
unsigned int j;
for (i = start - 1; i >= 0; i--)
{
j = i;
if (j >= number1.array.size())
{
one_value = 0;
}
None of these seems particularly desirable. Can you suggest any alternative, or make a recommendation as to what I should do in this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这应该与您的代码相同 -
i
从start
运行到1
(而不是start-1
到0
) ,并且对数组大小的测试也做了相应的改变。This should work the same as your code -
i
runs fromstart
to1
(instead ofstart-1
to0
), and the test for the array size was changed accordingly.你可以尝试:
You could try:
首先,将有符号数分配给无符号类型可能会产生相当严重的后果(有符号 32 位类型中的 -1 是无符号中的 4 294 967 295),这是该警告存在的原因之一。您可以在两种解决方案中的一个位置或另一个位置进行转换,无论您使用哪一个,只需将 size() 转换为有符号整数即可获得相同的效果。
沿着这些思路的东西可以消除该漏洞(未检查正确性) :)
我认为,
First of all, assigning a signed number to an unsigned type could have quite serious consequences (-1 in a signed 32-bit type is 4 294 967 295 in an unsigned), which is one of the reasons for that warning existing. You do the conversion in one place or the other in both solutions, and no matter which of them you use, you would get the same effect by just casting size() to a signed integer.
Something along these lines would eliminate the vulnerability (not checked for correctness)
I think :)
使用“size_t”进行与大小相关的比较。
use 'size_t' for size related comparisons.
“由于循环中的测试是 i >= 0,所以 i 必须被签名,否则不起作用。”只需像这样更改您的测试:
在循环体中为您提供相同的 i 值。
"Since the test in the loop is i >= 0, i has to be signed or it doesn't work." Just change your test like this:
Gives you the same value of i in the loop body.