"没有声明"之间的区别并继续

时间:2014-12-31 22:39:19

标签: c continue

在下面的代码中,请查看具有“continue”语句的部分。如果我删除“继续”声明并且我没有放任何东西,它会有什么不同。

int prime_or_not(int x){
    int i;
    if (x == 1 || x == 2){
        return 1;
    }else if (x % 2 == 0){
        return 0;
    }else if (x > 2){
        for (i = 3; i < x; i += 2){
            if (x % i == 0){
                return 0;
                break;
            }else {
                continue;
            }
        }
        return 1;
    }else {
        return 0;
    }
}

6 个答案:

答案 0 :(得分:6)

根本没有任何区别。 continue语句是跳转语句。基本上,它跳回你的循环而不执行它之后的代码。 由于continue语句最后在循环中执行,因此无效。

答案 1 :(得分:5)

它对您的代码没有任何影响,但请考虑这样的事情:

(伪代码):

for(int i = 10; i > -5; i--) {
    if(i == 0)
        continue;

    printf("%d", 10/i);
}

答案 2 :(得分:3)

'continue'直接跳到'for'或'while'括号的末尾,“}”。在你的情况下,因为在continue关键字之后没有任何内容,所以没有任何区别。

为了说清楚,通常情况下,'继续'和没有声明之间存在很大差异。例如,

for (code-condition){
 code-1
 code-2
 continue;
 code-3
 code-4
}

执行'continue'行后,它会直接跳到结束“}”,忽略代码-3和代码4。在这里执行的下一段代码是代码条件。

答案 3 :(得分:2)

在你的情况下,没有区别。

然而,如果有任何代码,则continue会立即转到循环的下一次迭代,并跳过后面的任何代码。

考虑一下:

int x;
for(x = 0; x < 100; x++){
    if(x == 50){
        //do something special
        continue;
    }
    //code here is skipped for 50
    //do something different for every other number
}

因此,在某些情况下,continue语句可能很有用,但对于你的代码,它完全没有任何区别(可能取决于编译器,但它只会增加最终可执行文件的大小,添加另一个jmp指令,或者也许不是因为它可以完全解开循环。

答案 4 :(得分:2)

我会简化块

    for (i = 3; i < x; i += 2){
        if (x % i == 0){
            return 0;
            break;
        }else {
            continue;
        }
    }

    for (i = 3; i < x; i += 2){
        if (x % i == 0){
            return 0;
        }
    }

其他行不会改变代码的行为。

答案 5 :(得分:2)

continue语句在您的示例中没用。它应该用于将代码执行移动到循环的结尾:

while (is_true)
  {
    ...

    if (foo)
      continue;

    if (bar)
      break;

    ...

    /* 'continue' makes code jump to here and continues executing from here */
  }
/* 'break' makes code jump to here and continues executing from here */

您可以将continue视为“评估循环条件并在条件为假时继续循环”,并且您可以将break视为“退出循环,忽略循环条件”

do-while相同:

do
  {
    ...

    if (foo)
      continue;

    if (bar)
      break;

    ...

    /* 'continue' moves execution to here */
  }
while (is_true);
/* 'break' moves execution to here */
相关问题