If I declare a variable inside a for loop in C, will it be created multiple times or not?

Viewed 1729
#include <stdio.h>

int main()
{
    for(int i=0;i<100;i++)
    {
        int count=0;
        printf("%d ",++count);
    }
    return 0;
}

output of the above program is: 1 1 1 1 1 1..........1

Please take a look at the code above. I declared variable "int count=0" inside the for loop. With my knowledge, the scope of the variable is within the block, so count variable will be alive up to for loop execution. "int count=0" is executing 100 times, then it has to create the variable 100 times else it has to give the error (re-declaration of the count variable), but it's not happening like that — what may be the reason?

According to output the variable is initializing with zero every time.

Please help me to find the reason.

4 Answers

Such simple code can be visualised on http://www.pythontutor.com/c.html for easy understanding.

To answer your question, count gets destroyed when it goes outside its scope, that is the closing } of the loop. On next iteration, a variable of the same name is created and initialised to 0, which is used by the printf.

And if counting is your goal, print i instead of count.

int count=0 is executing 100 times, then it has to create the variable 100 times

No, it defines the variable count once, then assigns it the value 0 100 times.

  • Defining a variable in C does not involve any particular step or code to "create" it (unlike for example in C++, where simply defining a variable may default-construct it). Variable definitions just associate the name with an "entity" that represents the variable internally, and definitions are tied to the scope where they appear.

  • Assigning a variable is a statement which gets executed during the normal program flow. It usually has "observable effects", otherwise the compiler is allowed to optimize it out entirely.

OP's example can be rewritten in a completely equivalent form as follows.

for(int i=0;i<100;i++)
{
    int count;  // definition of variable count   - defined once in this {} scope
    count=0;    // assignment of value 0 to count - executed once per iteration, 100 times total

    printf("%d ",++count);
}

The C standard describes the C language using an abstract model of a computer. In this model, count is created each time the body of the loop is executed, and it is destroyed when execution of the body ends. By “created” and “destroyed,” we mean that memory is reserved for it and is released, and that the initialization is performed with the reservation.

The C standard does not require compilers to implement this model slavishly. Most compilers will allocate a fixed amount of stack space when the routine starts, with space for count included in this fixed amount, and then count will use that same space in each iteration. Then, if we look at the assembly code generated, we will not see any reservation or release of memory; the stack will be grown and shrunk only once for the whole routine, not grown and shrunk in each loop iteration.

Thus, the answer is twofold:

  • In C’s abstract model of computing, a new lifetime of count begins and ends in each loop iteration.
  • In most actual implementations, memory is reserved just once for count, although implementations may also allocate and release memory in each iteration.

However, even if you know your C implementation allocates stack space just once per routine when it can, you should generally think about programs in the C model in this regard. Consider this:

for (int i = 0; i < 100; ++i)
{
    int count = 0;
    // Do some things with count.
    float x = 0;
    // Do some things with x.
}

In this code, the compiler might allocate four bytes of stack space to use for both count and x, to be used for one of them at a time. The routine would grow the stack once, when it starts, including four bytes to use for count and x. In each iteration of the loop, it would use the memory first for count and then for x. This lets us see that the memory is first reserved for count, then released, then reserved for x, then released, and then that repeats in each iteration. The reservations and releases occur conceptually even though there are no instructions to grow and shrink the stack.

Another illuminating example is:

for (int i = 0; i < 100; ++i)
{
    extern int  baz(void);
    int a[baz()], b[baz()];

    extern void bar(void *, void *);
    bar(a, b);
}

In this case, the compiler cannot reserve memory for a and b when the routine starts because it does not know how much memory it will need. In each iteration, it must call baz to find how much memory is needed for a and how much for b, and then it must allocate stack space (or other memory) for them. Further, since the sizes may vary from iteration to iteration, it is not possible for both a and b to start in the same place in each iteration—one of them must move to make way for the other. So this code lets us see that a new a and a new b must be created in each iteration.

Eric has it correct. In much shorter form:

Typically computer determine at compile time how much memory is needed by a function and where the variables will be in the stack. There is no individual allocation/release of stack memory.

Further, when you have variables nested within {curly braces} once execution leaves that brace set the compiler is free to reuse that memory for other variables in the function. There are two reasons I intentionally do this:

  • The variables are large but only needed for a short time so why make stacks larger than needed?
  • If a variable only has a sane value for a limited amount of time, and would be dangerous or buggy to use out of that scope, add extra curly braces so improper use generates a compiler error.

Example:

your_function(int a)
{
   int stack_1;
  { 
     int limited_scope_1[10000];
     do_something(a,limited_scope_1);
  }
  { 
     int limited_scope_2[10000];
     do_something_else(a,limited_scope_2);
  }       
}
Related