Define Variable once in function or scope and don't delete its value after its done

So far I looked this up on Google multiple ways and I can't find what I'm looking for.

What I would like to do is call a function I made, and inside that function is a variable that I declared lets say "int count=0"

I only want count to initialize to 0 the first time that function is called and after that just increment it once ie count++;

The thing is though that every time the function is called count will be deleted and created hence it will always be 0. I don't want count to be reset every time the function is called.

like if I called my function 3 times in a row

call 1: function will return 1
call 2: function will return 2
call 3: function will return 3 and etc

What I don't want is the var to be deleted after the function is finished executing and then initialize it again when the function is called on again and I don't want the variable to be declared outside of the function.

thank you.

This is what I looked up on Google and didn't find what i was looking for:

c++ Declare variable once in function or scope
c++ Define variable once in function or scope
c++ Do not destroy variable when the function is done
c++ Do not reset var within function
That's called static storage duration:
int f()  {
    static int count = 0; // on the first call
    return ++count; // on every call
Last edited on
When I looked that up they kept saying that if you use static that it can only hold a single value and that it cannot be changed during run time and all.

Unless I read that wrong

Thanks again, i'll try that out asap
Topic archived. No new replies allowed.