为什么“ for”循环条件失败? [英] Why does the 'for' loop condition fail?

查看:152
本文介绍了为什么“ for”循环条件失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面显示的代码中,没有任何输出,这意味着 for 循环中的条件失败。

In the code shown below, nothing gets printed, which means the condition in the for loop fails. What could be the reason?

我想知道是因为当我分别打印 TOTAL_ELEMENTS 时,它会给出 5 ,因此自然地,该值必须为 5-2 = 3 => -1< = 3 ,因此它应该打印一些内容。

I'm wondering because when I print TOTAL_ELEMENTS separately, it gives 5, so naturally this must be 5-2=3 => -1<=3, so it should print something.

#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))

int array[] = { 23, 34, 12, 17, 204, 99, 16 };
int main()
{
    int d;

    for (d = -1; d <= (TOTAL_ELEMENTS - 2); d++) {
        printf("%d\n", array[d + 1]);
    }

    return 0;
}

有人可以解释此代码吗?

Can someone explain this code?

推荐答案

这是常规算术转换的结果。

This is a result of the "usual arithmetic conversions".

来自< a href = http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf> C标准:


如果两个操作数具有相同的类型,则不需要进一步转换

If both operands have the same type, then no further conversion is needed.

否则,如果两个操作数都具有有符号整数类型或两者都有
无符号整数类型,则将
整数转换等级较小的操作数转换为具有较高等级的操作数
的类型。

Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.

否则,如果具有无符号整数类型的操作数的
等级大于或等于其他
操作数的类型的等级,则操作数为有符号整数类型是
转换为无符号操作数的类型

否则,如果带符号整数类型的操作数的类型可以
表示整数的所有值无符号
整数类型的操作数的类型,则无符号整数类型的操作数为
转换为带符号整数类型的操作数的类型。

Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.

否则,两个操作数都将转换为与带符号
整数类型的操作数类型相对应的无符号
整数类型。

Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

sizeof 运算符返回 size_t ,这是一个无符号值。因此(sizeof(array)/ sizeof(array [0]))-2 也未签名。

The sizeof operator returns a size_t, which is an unsigned value. So (sizeof(array) / sizeof(array[0])) - 2 is also unsigned.

因为您正在比较一个带符号的值和一个无符号的值,则带符号的值将转换为无符号。将-1转换为unsigned会导致最大的unsigned值,这会导致比较为假。

Because you are comparing a signed and an unsigned value, the signed value is converted to unsigned. Converting -1 to unsigned results in the largest unsigned value, which results in the comparison being false.

如果将右侧投影到 int ,它将按预期工作。

If you cast the right hand side to int, it will work as expected.

for(d=-1;d <= (int)(TOTAL_ELEMENTS-2);d++)

输出:

23
34
12
17
204
99
16

或者您可以通过规范索引数组的方式来避免此问题:

Or you could avoid the issue by normalizing how you index the array:

for (d = 0; d < TOTAL_ELEMENTS; d++) {
    printf("%d\n", array[d]);
}

这篇关于为什么“ for”循环条件失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆