C Programming: Memory, Pointers and the Stack ยท Control Flow

break and continue

Skip a bad value with continue and stop at a sentinel with break.

break_continue.c

#include <stdio.h>

int main(void) {
    int nums[6] = {3, -1, 4, 0, 5, 9};
    int total = 0;
    for (int i = 0; i < 6; i++) {
        if (nums[i] < 0) {
            continue;
        }
        if (nums[i] == 0) {
            break;
        }
        total += nums[i];
    }
    printf("total = %d\n", total);
    return 0;
}

Step by step

  1. nums is created on the stack with the value [3, -1, 4, 0, 5, 9].
  2. total is created on the stack with the value 0.
  3. i is created on the stack with the value 0.
  4. C checks nums[i] < 0 to decide which way the code goes.
  5. C checks nums[i] == 0 to decide which way the code goes.
  6. A good value: total = 3.
  7. i changes from 0 to 1.
  8. C checks nums[i] < 0 to decide which way the code goes.
  9. -1 is negative: continue jumps to the next round (i++).
  10. i changes from 1 to 2.
  11. C checks nums[i] < 0 to decide which way the code goes.
  12. C checks nums[i] == 0 to decide which way the code goes.
  13. total changes from 3 to 7.
  14. i changes from 2 to 3.
  15. C checks nums[i] < 0 to decide which way the code goes.
  16. C checks nums[i] == 0 to decide which way the code goes.
  17. 0 means stop: break leaves the loop.
  18. It prints total = 7.
  19. The method returns 0.
  20. total = 7 (3 + 4).