Question: "Write a function which will return 100 the first time it's called, the second time it's called it should return 99, third 98, etc. - once the number reaches zero, function should always return 0".

I'm absolutely lost here, because it could easily be done via

```
int func()

{

int x = 100;

if ( x == 0 )
return 0;
else
return x;

--x;

}

```

but that obviously doesn't work. Any help?

Answer: 
Try this:

```
#include <stdio.h>

int func(void) {
        static int x = 100;
        return x ? x-- : 0;
}

int main(void) {
        int i;
        // Until 105 to see that it always returns 0 after 100 calls
        for(i = 0; i < 105; ++i)
                printf("%d\n", func());
        return 0;
}

```

The `static` keyword says that `x`'s value should not be vanished, after the termination of `func()`, so that when `func()` is called for the second time, `x` will have the same value as on the termination of `func()`.

Note that `static int x = 100;` will be executed once, that means that `x` won't receive value 100 on second call of `func()`.

---

If confuses `return x ? x-- : 0;` you, it's just equivalent to this:

```
if(x == 0)
    return 0;
return x--;

```
Define your function like this:
-------------------------------

```
    int func() 
     {
        static int x = 100;
        if (x==0)
            return 0;
        else
            return x--;
     }

```

---

The magic happens because of the static qualifier attached to integer variable.
static variables are part of the data section of your program even though it is declared and defined inside a function. The data section gets initialized once at the time the program is loaded. So when you call this function, the static int x will be initialized 100 only once.