-1

I have this code right here:

#include <iostream>
using namespace std;

int main() {
  int counter = 0;
  int sum = 0;
  while(counter < 10);
  {
    sum += ++ counter;
  }
  cout << sum << endl;
}

I was wondering if the line while(counter < 10); is an infinite loop which results in the rest of the code not being executed.

Another side question, since the while is delimited with ;, that block of code under it is just an inner scope of code?

Blanker
  • 51
  • 1
  • 4
  • 1
    The code wont continue beyond `while`. Also I dont think you can call the code inside `{ }` inner scope since if you comment out the `while` the code inside `{ }` will run by itself. In this case commenting out `while(counter < 10);` will give you a sum of 1. – D.H. Nov 15 '17 at 02:39

2 Answers2

2

Yes, as the initial value of counter is 0 then the statement

while (counter < 10);

which is implicitly

while (counter < 10) {}

is an infinite loop. And yes, due to the terminating semi-colon on the while statement, the subsequent braced block is just another scope.

donkopotamus
  • 22,114
  • 2
  • 48
  • 60
1

The code while(counter < 10); causes undefined behaviour due to not making forward progress on a thread.

In practice this might mean that execution hangs, or execution skips over that line, or anything else. The compiler might optimize the whole program to output 1, or 11.

For further reading see Forward progress - progress guarantee

M.M
  • 138,810
  • 21
  • 208
  • 365
  • Is the reason for it's discontinuity because the loop is executing but never able to evaluate the conditional as false? – Blanker Nov 15 '17 at 03:12
  • @Blanker You could look at the assembly output generated by your compiler to get a hint of what is happening on your system. – M.M Nov 15 '17 at 03:13
  • I have this to look at: https://godbolt.org/g/Gjg8Kz but I personally don't know what any of the assembly means, except that maybe since it has no `ret` command (again, very little knowledge of asm) I assume the `jmp` means it keeps looping. – Blanker Nov 15 '17 at 03:21
  • 1
    @Blanker yes, `jmp .LBB0_1` means that execution jumps to the label `.LBBO_1:` – M.M Nov 15 '17 at 03:25