C 区别于;“无声明”;继续

C 区别于;“无声明”;继续,c,continue,C,Continue,在下面的代码中,请查看包含“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 +

在下面的代码中,请查看包含“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;
    }
}
int素数或非素数(int x){
int i;
如果(x==1 | | x==2){
返回1;
}如果(x%2==0),则为else{
返回0;
}如果(x>2),则为else{
对于(i=3;i
这根本没什么区别。
continue
语句是一个跳转语句。基本上,它会跳回您的循环,而不是在它之后执行代码。
由于
continue
语句是循环中最后一次执行的,因此它没有任何效果。

它对代码没有影响,但请考虑以下情况:

(伪代码):


在你的情况下,没有区别

然而,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
}
intx;
对于(x=0;x<100;x++){
如果(x==50){
//做点特别的事
继续;
}
//这里的代码被跳过50分钟
//对其他数字做一些不同的处理
}

因此,continue语句在某些情况下可能很有用,但对于这里的代码来说,它绝对没有任何区别(可能取决于编译器,但它只会增加最终可执行文件的大小,添加另一条jmp指令,或者可能不会,因为它可能会完全释放循环).

我会简化程序块

    for (i = 3; i < x; i += 2){
        if (x % i == 0){
            return 0;
            break;
        }else {
            continue;
        }
    }
(i=3;i{ 如果(x%i==0){ 返回0; 打破 }否则{ 继续; } }

(i=3;i{ 如果(x%i==0){ 返回0; } }
附加的行不会更改代码的行为。

在您的示例中,
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
视为“评估循环条件并在条件为false时继续循环”,也可以将
break
视为“退出循环,忽略循环条件”

边做边做同样的事情

do
  {
    ...

    if (foo)
      continue;

    if (bar)
      break;

    ...

    /* 'continue' moves execution to here */
  }
while (is_true);
/* 'break' moves execution to here */

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

简单地说,正常情况下,“继续”和“不声明”之间有很大区别。比如说,

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

一旦执行了“continue”行,它将直接跳转到结束“}”,忽略代码3和代码4。这里执行的下一段代码是代码条件。

在调试器中单步执行后,您发现了什么?不需要使用
中断
继续
。顺便说一句,1不是质数。有些人以“最佳实践”的名义对于每个
if
,将始终有一个
else
。在显示的代码中,给定的
else{continue;}
、空的
else{}
、以及没有
else
都具有相同的效果。另外,在
返回之后加上一个中断是不可访问的代码。关于这一行:'for(i=3;i>1);i+=2){'@iKiWiXz,它现在是固定的:)
do
  {
    ...

    if (foo)
      continue;

    if (bar)
      break;

    ...

    /* 'continue' moves execution to here */
  }
while (is_true);
/* 'break' moves execution to here */
for (code-condition){
 code-1
 code-2
 continue;
 code-3
 code-4
}