- [Tutor] Variables declared in a function default
to automatic storage.
Other storage options are also available.
Here is func dot cpp from chapter five
of the exercise files.
And if I come down here into my function
and I declare variable,
and then I print it.
When I build and run,
you'll notice that it says i is five
because the function is of course called
down here on line 14.
Now, if I increment i after I print it
and then let's say, we call this a few times.
When I build and run you'll notice that
the value's the same each time.
And that's because every time this block is called,
every time this function is called
a new copy of i is created.
and that's because it's in automatic storage.
The default for a variable inside a block,
which means inside a function or a loop,
the default is for that variable to be automatic storage,
defaults to automatic storage.
And automatic storage is stored on the stack,
which is temporary
and the value is not carried on
from one invocation to another.
If I declare this as static storage,
now you'll notice when I run this,
that the value increments each time the function is called.
You notice down here,
it says i is five, six, seven and eight
because the function is called four times
and we're incrementing the value each time.
And because this is now in static storage,
it's no longer on the stack,
it's now in the main memory pool.
And that same variable is reused each time
and its value is carried forward each time.
Whereas with automatic storage,
it's created fresh each time
and the value is not carried forward
from one invocation to the other.
Because automatic storage is stored on the stack,
it is not suitable for large objects.
It's always a good idea to avoid using
automatic storage for anything larger
than a few scalar variables.
Important note here,
it used to be possible to declare a variable as auto,
it used to be able to say this.
And you'll notice if I try to build this
it's deprecated here
and says, it won't be supported in future releases,
replace auto with nothing.
So the current standard and in recent compilers,
the auto keyword
no longer works as a storage class modifier.
It was never really used
because it's always been the default storage class.
So even when it was allowed,
nobody ever used it.
And so the auto keyword has now been repurposed
for automatic typing,
which we'll discuss elsewhere in this course.
So variables declared in a function default
to automatic storage.
If you want your data to be persistent,
that is carried forward from one invocation to another.
You may declare your variables as static
and we'll cover other types of memory allocation
later in this course.