-2

if the variable is initialized (i = 0), it's still 1 each time the function func is called, BUT

when i is not initialized:

#include <stdio.h>

int funct(void);
int main(void)
{
    funct();
    funct();
    funct();

    return 0;
}

int funct(void)
{
    int i;  
    static int j = 0;

    i++;
    j++;

    printf(" i = %d         j = %d\n", i, j);
}

the output is

 i = 1      j = 1
 i = 2      j = 2
 i = 3      j = 3

I don't understand why the variable i behaves like a static one!

Abion47
  • 22,211
  • 4
  • 65
  • 88
Ura
  • 3
  • 2
  • 2
    It can behave as a pink unicorn, as the behavior of this code is undefined. – Eugene Sh. Feb 20 '19 at 22:04
  • 1
    Undefined behaviour includes doing what you expect; the function is called repeatedly, there is no reason to think it will change memory addresses. – Neil Feb 20 '19 at 22:05
  • This is a complete guess, but I'd think that your compiler/runtime is initializing `i` at the same address in memory on each calling of the function and, because you don't instantiate `i` afterwards, inherits its previous value. – Abion47 Feb 20 '19 at 22:07
  • @ Abion47 so .. does it depend on the type of the compiler? – Ura Feb 20 '19 at 22:13
  • @Ura It can depend on what compiler you're using, on the time of day the program runs, on the activity of solar winds, on ... but to answer your question, no, `i` is not `static`. `i` has [indeterminate value](https://stackoverflow.com/questions/13423673/what-is-indeterminate-value) and when you increment an indeterminate value you get another indeterminate value. – Swordfish Feb 20 '19 at 22:33
  • When a variable is unitialised, it will *typically* have whatever value happens to be in the memory in which the variable is instantiated. Because in this case you are simply calling the same function repeatedly with no intermediate code, the stack frame will be established at the same location each time, so the variable will be instantiated at the same address each time, and that memory is not explicitly modified by initialisation. – Clifford Feb 20 '19 at 23:58

1 Answers1

4

The value is unspecified, so anything goes. But, likely the same memory is reused for each call to funct and with that, the same memory is reused and the i just pick up the old value left from the previous run.

Bo R
  • 2,334
  • 1
  • 9
  • 17