C - One More scope inside do while loop

Introduction

In the following code you have two variables called count.

Inside the do-while loop block the local variable will "hide" the version of count that exists at the main() block level.

The compiler will assume that when you use the name count, you mean the one that was declared in the current block.

Inside the do-while loop, only the local version of count can be reached.

The printf() inside the loop block displays the local count value, which is always 1.

As soon as you exit the loop, the outer count variable becomes visible, and the last printf() displays its final value from the loop as 6.

Demo

#include <stdio.h>

int main(void)
{
  int count = 0;                                // Declared in outer block
  do/*from ww w.  j a va 2  s .  c  om*/
  {
    int count = 0;                              // This is another variable called count
    ++count;                                    // this applies to inner count
    printf("count = %d\n", count);
  } while (++count <= 5);                // This works with outer count

  printf("count = %d\n", count);       // Inner count is dead, this is outer count
  return 0;
}

Result

Related Topic