C For循环在执行条件false后仍然递增
我是C语言的新手,所以这个问题很可能有一个简单的解决方案,但我看不出来。我注意到我的输出并不是我所期望的,经过几个小时的调试,我意识到我的一个for循环没有按预期的那样运行。以下是我代码的相关部分:C For循环在执行条件false后仍然递增,c,for-loop,C,For Loop,我是C语言的新手,所以这个问题很可能有一个简单的解决方案,但我看不出来。我注意到我的输出并不是我所期望的,经过几个小时的调试,我意识到我的一个for循环没有按预期的那样运行。以下是我代码的相关部分: for (i = 0; i < bytes; i++) { if ((temp_array[i]) == 0xCADE | (temp_array[i]) == 0xDADA) { printf(
for (i = 0; i < bytes; i++)
{
if ((temp_array[i]) == 0xCADE | (temp_array[i]) == 0xDADA)
{
printf("i is %d\n",i );
i += 2;
printf("i is now %d\n",i );
n_body = temp_array[i];
i++;
printf("n_body is %d\n",n_body );
for (count = 0, j = flag_index; count < n_body; i++, j++, count++)
{
machine->memory[j] = temp_array[i];
printf("LETS SEE, i in loop is %d\n",i );
printf("LETS SEE, j in loop is %d\n",j );
printf("LETS SEE, count in loop is %d\n", count);
}
printf("\n");
printf("LETS SEE, i out of loop is %d\n",i );
printf("LETS SEE, j out of loop is %d\n",j );
printf("LETS SEE, count out of loop is %d\n", count);
machine->memory[j+1] = flag;
//printf("flag is %d\n",flag );
printf("machine memory index 18 is %d \n", machine->memory[18]);
}
// else
// {
// continue;
// }
//printf("index is %d\n",i );
}
为什么它们在增加?我认为一旦执行条件不再为真,for循环就会关闭(执行body和pre-post增量)?它会更新任何变量,然后测试条件。如果条件为真,它会再次出现。如果为false,则退出。所以如果你有(x=0;x<5;++x)的
如果在循环外打印代码>x,其值将为5(x必须为5,否则x<5为假)
如果搜索,您可以在线找到for循环的流程图。这里有一个来自Geeksforgeks的:
这是正常的。你可以通过一个小的演示程序看到
#include <stdio.h>
int main() {
int i = 0;
for( i = 0; i < 3; i++ ) {
printf("i in loop: %d\n", i);
}
printf("i after loop: %d\n", i);
}
$ ./test
i in loop: 0
i in loop: 1
i in loop: 2
i after loop: 3
所以你的内环相当于
// for (count = 0, j = flag_index; count < n_body; i++, j++, count++) {
count = 0, j = flag_index;
while( count < n_body ) {
machine->memory[j] = temp_array[i];
i++, j++, count++;
}
//for(count=0,j=flag\u index;count内存[j]=临时数组[i];
i++,j++,count++;
}
您确定要按位或
而不是逻辑或
吗?如果计数<18
失败,计数必须达到18
…不确定为什么希望它在17结束。您在两个循环中递增i
,例如为(i=0;i
…(count=0,j=flag_索引;count
@Schwern,谢谢你的提示。我确实想要一个逻辑OR,这是我的一个错误。谢谢。示例程序澄清了我的错误。看起来我必须手动减少for循环之外的索引变量,以便它们具有我在程序其余部分所需的值。我希望有一种更精简的方法虽然。。。
// for( int i = 0; i < 3; i++ ) {
int i = 0;
while( i < 3 ) {
printf("i in loop: %d\n", i);
i++;
}
// for (count = 0, j = flag_index; count < n_body; i++, j++, count++) {
count = 0, j = flag_index;
while( count < n_body ) {
machine->memory[j] = temp_array[i];
i++, j++, count++;
}