在C编程中,for(int i = 0; st [i]; i ++)和for(int i = 0; i <st [length of =“” the =“” array]; i ++)=之间有什么区别? “”

时间:2019-01-31 20:36:35

标签: c arrays for-loop conditional-statements garbage

=“”

在以下程序中,同时在for循环条件上使用st [i]:

#include<stdio.h> 
int main() 
{ 
     int st[] ={1,2,3,4,5,6,7,8}; 
     int i; 
     for(i=0; st[i]; i++) 
         printf("\n%d %d %d %d", str[i], *(str+i), *(i+str), i[str]); 
     return 0;
}   

输出:

1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6
7 7 7 7
8 8 8 8
-874149648 -874149648 -874149648 -874149648
32764 32764 32764 32764

在下面的程序中,在for循环条件下使用i <8:

#include<stdio.h> 
int main() 
{ 
     int str[8] ={1,2,3,4,5,6,7,8}; 
     int i; 
     for(i=0; i<8; i++) 
         printf("\n%d %d %d %d", str[i], *(str+i), *(i+str), i[str]); 
     return 0;
}  

输出: 输入

1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6
7 7 7 7
8 8 8 8

任何人都可以在st [i]中解释一下发生了什么。如果它是垃圾值,那么为什么它在打印两次额外的迭代后就停止了。

编译器:onlinegdb.com -c编译器

3 个答案:

答案 0 :(得分:4)

只要中间表达式的值为true,即非零值,for循环就会继续。因此,在这种情况下:

for(i=0; st[i]; i++) 

只要st[i]不为0,循环就会继续。由于数组中没有包含0的元素,因此最终将读取数组的末尾。这样做会调用undefined behavior,在这种情况下,https://stackoverflow.com/a/20045505/8397835表现为不确定数量的看似随机值的打印。

答案 1 :(得分:2)

在C中,条件的结果为非零,则为true;如果结果为零,则为false。

在条件简单为st[i]的情况下,它会隐式比较st[i]的值和零,以确定条件是真还是假。在处理长度未知的字符串(即,是否将其作为指针传递)时,这是很常见的事情,因为空终止符的数值为零。

在您的情况下,比较没有任何意义,因为int数组的结尾不是零,而且您已经知道它的长度。为什么不只是通过8? st[i]的条件将调用未定义的行为,因为可以保证您不受该数组的限制,因为其中不包含任何值为零的元素。

答案 2 :(得分:2)

driver = new ChromeDriver(chromeDriverService, options); DockPanel.Children.Add(driver); 在某些不可预测的迭代中可能会变为零(这在C语言中为false),这是因为您读取了数组末尾的元素。这是UB,可能会发生任何事情。

修改

st[i]

它将按预期工作