The difference between continue, break, and return in C/C++

1. The function of the return statement
      (1) return Exit from the current method, return to the statement of the called method, and continue execution.
      (2) return returns a value to the statement that calls the method. The data type of the return value must be the same as the type of the return value in the method declaration.
      (3) Return can also be followed by no parameters. Without parameters, it returns empty. In fact, the main purpose is to interrupt the execution of the function and return to the calling function.
  2. The role of the break statement
    (1) Break is in the loop body, forcibly ending the execution of the loop, that is, ending the entire loop process, instead of judging whether the conditions for executing the loop are established, it directly turns to the statement below the loop statement.
    (2) When break appears in the body of the switch statement in the loop body, its function is only to jump out of the body of the switch statement.
  3. The function
      of the continue statement terminates the execution of this loop, that is, skips the statements that have not been executed after the continue statement in the current loop, and then judges the next loop condition.

  Let's take a look at an example to make it clearer:

#include <stdio.h>
intmain()
{
    int i = 5,n = 0;
    while(i--)
    {
        if(i == 3)
     // return;
     // break;
        continue;
        else if(i == 1)
            n = 6;
    }
    n = n + 5;
    printf("i=%d\n",i);
    printf("n=%d\n",n);
        return 0;    
}

When running continue, the result is:

i=-1
n=11

When running break, the result is:

i=3
i=5
When running return, there is no result, indicating that when i==3 is executed, the main function has been brought out, and the following statement will not be executed.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325932937&siteId=291194637