Local Static in C++

The Cherno · Intermediate ·8y ago

Key Takeaways

The video discusses the use of the static keyword in C++ to declare variables with extended lifetime and limited scope, and demonstrates its application in creating Singleton classes and persisting variables between function calls. The static keyword is used in local scope to extend the lifetime of variables, and its behavior is tested with and without the static keyword.

Full Transcript

hey what's up guys My Name Is AO and welcome back to my C++ series over the last couple of episodes we took a look at what the static keyword meant in certain contexts and today we're going to have a look at one other context that you might find the static keyword in and that is in a local scope so you can actually use static in a local scope to declare a variable and that has a bit of a different meaning than the other two Statics that we've looked at and the idea behind this meaning makes a lot more sense if you think about the two kind of considerations we have to make when we're declaring a variable and that is the lifetime of the variable and the scope of the variable the lifetime refers to how long that variable will actually stick around for in other words how long it will remain in our memory before it gets deleted and then the scope refers to where we can actually access that variable so of course if we declare a variable inside a function for example we can't just access it in another function because the variable we declared is going to be local to the function we declared it in so a static local variable allows us to declare a variable that has the lifetime of essentially our entire program however its scope is limited to be inside that function and this really has nothing to do with functions in particular I mean you can declare this in any scope really I'm just using function as an example it's not really just limited to being inside a function could be inside an if statement could be anywhere which is why again there's not much of a difference between static in a function scope versus static in a class scope because the lifetime is actually going to be the same the only difference is that the one in the class scope anything in the class can access it anything that has anything that is inside that class scope can access that static variable however of course if you declare one inside a function scope it's going to be local to that function instead of being local to that class let's jump in and take a look at some examples so the simplest example is going to be just to create a function and then declare some kind of static variable inside it so I'll just make static in I equals z what this means is that when I call function for the first time this variable will be initialized to zero and then on subsequent calls to functions it's not actually going to create a brand new variable really easy way to check this out is if I just print the value of I and then I increment it every time I call the function so if we didn't have static here what you would expect is that every time you call this function I gets set to zero then I gets incremented to one and then we print one to the console and in fact we can test that out by just calling function a whole bunch of times here we'll call it five times we'll hit our five to run our program and you can see that we get one printing five times because as I just explained we create a variable every single time and we set it equal to zero we then increment it to one and then we print that to the console now if we were to make this static then it's very very similar to if we had just moved this original declaration out here so if we run this code and it doesn't really matter if this has static or not in our case it's going to be the same if you want to know more about what static does in that sense you can check out the video that's linked somewhere so if I run this code you would expect I to be zero increment Ed five times and so you'll get 1 2 3 4 5 which is exactly what you get however the problem with this approach is that I can access I anywhere I could set I equal to 10 over here in between function calls and suddenly this dramatically changes what my program does so for cases where you want this kind of behavior however you do not want to give everyone access to that variable you can declare static in a local scope so let's get rid of this and move our I variable back into the function scope I'm going to stick static out the front which means that again the first time we we run this function it's going to set it equal to zero and create the variable in the first place then on subsequent times it's just going to refer to that original variable so if I run my code now you can see I get 1 2 3 4 5 and I get the exact same behavior as I did before however that I variable isn't visible in a global scope it's just local to that function now as for uses some people do like to discourage the use of this because of certain reasons that I don't fully understand because I don't really see a problem with this it definitely has its use it's one of those things where yes you can achieve the exact same behavior using other methods however that can also be said for classes you don't necessarily have to use classes at all to write a program however it does make your life easier same with this case it's one of those things that you can just do to keep your code a little bit cleaner another example might be if you had a Singleton class so a Singleton class is a class that should only have one instance in existence if I wanted to create this Singleton class without using this static local scope thing I would have to create some kind of static Singleton instance probably a pointer at this rate I'll set it here I would have to have a if I just wanted to return a normal reference I would have to have a Singleton reference returning get function which was static and returned my instance after dereferencing it of course I would then have to actually declare this instance over here Singleton Singleton as instance and we can probably set it equal to non pointer as a default and now I have the ability let's get rid of this now of course I have my Singleton class in which I can just call Singleton get and then do whatever I want with it so suppose we had a method here called hello don't really know what I'm doing just an example we could call that hello method and everything will be well you can see we've only got one instance of that class that we can use so we can kind of use it statically now this is quite a lot of code you don't necessarily have to do it this way another way to do this with our new found knowledge of this local static thing might be like this we can get rid of this entirely we can get rid of this external definition of s instance as well and then we can just expand our get function to actually create a static Singleton instance and then return that instance and there you go we get the exact same behavior you can see everything here stays the same we can run our code no problem of course the code is not actually going to do anything anything at this point but you can see it run successfully without crashing and we don't really have any problems with this at all and you can see that our code is a lot lot cleaner now of course if you didn't have the static keyword here then this Singleton since it is just created on the stack would get destroyed as soon as you hit this curly bracket and and then the function scope ends so this would be a grave error especially if you're returning it by reference if you're copying it of course you wouldn't really have a problem however since we are returning a reference to it this would would be a huge problem however by adding static where extending the lifetime of this to be essentially forever which means that every time we call get the first time it will actually construct that Singleton instance then on all subsequent times it will just return that existing instance so this is a great example of where you might want to use something like this it doesn't necessarily have to be with Singletons it can help you out a lot by replacing initialization functions where for example you might have to call a static initial where for example you might have to call a static initialization function at some point in your program to create all of your objects so that you could actually use the static get methods and stuff like that you can just kind of simplify that by using this in a lot of cases so you can see there are tons of uses for this and it's really not all that bad so feel free to use it that's my opinion let me know what you guys think of this static in a local scope thing in the comments below and I'll see you guys in the next video [Music] goodbye [Music] he

Original Description

Twitter ► https://twitter.com/thecherno Instagram ► https://instagram.com/thecherno Patreon ► https://patreon.com/thecherno Slack ► https://slack.thecherno.com In this video we take a look at yet another use of the static keyword in C++. Static can be used in a local scope to extend the lifetime of the variable to be essentially endless, rather than getting destroyed when the scope ends. Static in global scope ► https://youtu.be/f3FVU-iwNuA Static in class scope ► https://youtu.be/V-BFlMrBtqQ Series Playlist ► https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb BEST laptop for programming! ► http://geni.us/pakTES My FAVOURITE keyboard for programming! ► http://geni.us/zNhB FAVOURITE monitors for programming! ► http://geni.us/Ig6KBq MAIN Camera ► http://geni.us/t6xyDRO MAIN Lens ► http://geni.us/xGoDWT Second Camera ► http://geni.us/CYUQ Microphone ► http://geni.us/wqO6g7K
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from The Cherno · The Cherno · 0 of 60

← Previous Next →
1 3D Game Programming - Episode 1 - Window
3D Game Programming - Episode 1 - Window
The Cherno
2 3D Game Programming - Episode 2 - Game Loop
3D Game Programming - Episode 2 - Game Loop
The Cherno
3 3D Game Programming - Episode 3 - Arrays
3D Game Programming - Episode 3 - Arrays
The Cherno
4 3D Game Programming - Episode 4 - Drawing Pixels!
3D Game Programming - Episode 4 - Drawing Pixels!
The Cherno
5 3D Game Programming - Episode 4.5 - How Rendering Works
3D Game Programming - Episode 4.5 - How Rendering Works
The Cherno
6 3D Game Programming - Episode 5 - Playing with Pixels!
3D Game Programming - Episode 5 - Playing with Pixels!
The Cherno
7 3D Game Programming - Episode 6 - Performance Boosting
3D Game Programming - Episode 6 - Performance Boosting
The Cherno
8 3D Game Programming - Episode 7 - FPS Counter
3D Game Programming - Episode 7 - FPS Counter
The Cherno
9 3D Game Programming - Episode 8 - Alpha Support and More
3D Game Programming - Episode 8 - Alpha Support and More
The Cherno
10 3D Game Programming - Episode 9 - Beginning 3D
3D Game Programming - Episode 9 - Beginning 3D
The Cherno
11 3D Game Programming - Episode 10 - Floors and Animation
3D Game Programming - Episode 10 - Floors and Animation
The Cherno
12 3D Game Programming - Episode 11 - Rotation
3D Game Programming - Episode 11 - Rotation
The Cherno
13 3D Game Programming - Episode 12 - User Input
3D Game Programming - Episode 12 - User Input
The Cherno
14 3D Game Programming - Episode 13 - Render Distance Limiter!
3D Game Programming - Episode 13 - Render Distance Limiter!
The Cherno
15 3D Game Programming - Episode 14 - Basic Mouse Movement
3D Game Programming - Episode 14 - Basic Mouse Movement
The Cherno
16 3D Game Programming - Episode 15 - Textures + More!
3D Game Programming - Episode 15 - Textures + More!
The Cherno
17 3D Game Programming - Episode 16 - Walking, Crouching, Sprinting + More
3D Game Programming - Episode 16 - Walking, Crouching, Sprinting + More
The Cherno
18 3D Game Programming - Episode 16.5 - Exporting Runnable Jars
3D Game Programming - Episode 16.5 - Exporting Runnable Jars
The Cherno
19 3D Game Programming - Episode 17 - Small Adjustments + Birthday!
3D Game Programming - Episode 17 - Small Adjustments + Birthday!
The Cherno
20 3D Game Programming - Episode 17.5 - Creating an Applet
3D Game Programming - Episode 17.5 - Creating an Applet
The Cherno
21 3D Game Programming - Episode 18 - The Beginning of Walls
3D Game Programming - Episode 18 - The Beginning of Walls
The Cherno
22 3D Game Programming - Episode 18.1 - A Few More Things
3D Game Programming - Episode 18.1 - A Few More Things
The Cherno
23 Episode 18.5 - Creating an EXE File in Java
Episode 18.5 - Creating an EXE File in Java
The Cherno
24 3D Game Programming - Episode 19 - Rendering Walls
3D Game Programming - Episode 19 - Rendering Walls
The Cherno
25 3D Game Programming - Episode 20 - Continuing Walls, Fixing Bugs, and Managing Crashes
3D Game Programming - Episode 20 - Continuing Walls, Fixing Bugs, and Managing Crashes
The Cherno
26 3D Game Programming - Episode 21 - Texturing Walls, Fixing Clipping, and Fixing the Mouse
3D Game Programming - Episode 21 - Texturing Walls, Fixing Clipping, and Fixing the Mouse
The Cherno
27 3D Game Programming - Episode 22 - Random Level Generator + Properly Fixing Clipping
3D Game Programming - Episode 22 - Random Level Generator + Properly Fixing Clipping
The Cherno
28 3D Game Programming - Episode 23 - Graphical User Interface (GUI) Launcher
3D Game Programming - Episode 23 - Graphical User Interface (GUI) Launcher
The Cherno
29 3D Game Programming - Episode 24 - Making Our Launcher Work
3D Game Programming - Episode 24 - Making Our Launcher Work
The Cherno
30 3D Game Programming - Episode 25 - Writing and Reading Files
3D Game Programming - Episode 25 - Writing and Reading Files
The Cherno
31 3D Game Programming - Episode 26 - Custom Resolutions
3D Game Programming - Episode 26 - Custom Resolutions
The Cherno
32 3D Game Programming - Episode 27 - Decorating the Launcher
3D Game Programming - Episode 27 - Decorating the Launcher
The Cherno
33 3D Game Programming - Episode 28 - Continuing our Custom Launcher!
3D Game Programming - Episode 28 - Continuing our Custom Launcher!
The Cherno
34 3D Game Programming - Episode 29 - Launching The Game
3D Game Programming - Episode 29 - Launching The Game
The Cherno
35 3D Game Programming - Episode 30 - Colour Processing In-Depth
3D Game Programming - Episode 30 - Colour Processing In-Depth
The Cherno
36 3D Game Programming - Episode 31 - Sprites!
3D Game Programming - Episode 31 - Sprites!
The Cherno
37 3D Game Programming - Episode 32 - Sprite Mapping
3D Game Programming - Episode 32 - Sprite Mapping
The Cherno
38 3D Game Programming - Episode 33 - High Resolution Rendering
3D Game Programming - Episode 33 - High Resolution Rendering
The Cherno
39 3D Game Programming - Episode 34 - Entities
3D Game Programming - Episode 34 - Entities
The Cherno
40 Genesis - My Game for Ludum Dare 24
Genesis - My Game for Ludum Dare 24
The Cherno
41 Vlog + Ludum Dare Results
Vlog + Ludum Dare Results
The Cherno
42 Game Programming - Episode 1 - Resolution
Game Programming - Episode 1 - Resolution
The Cherno
43 Game Programming - Episode 2 - Threads
Game Programming - Episode 2 - Threads
The Cherno
44 Game Programming - Episode 3 - Game Loop
Game Programming - Episode 3 - Game Loop
The Cherno
45 Game Programming - Episode 4 - Window
Game Programming - Episode 4 - Window
The Cherno
46 Episode 5 - Buffer Strategy
Episode 5 - Buffer Strategy
The Cherno
47 Game Programming - Episode 6 - Graphics Initialized
Game Programming - Episode 6 - Graphics Initialized
The Cherno
48 Game Programming - Episode 7 - Buffered Image and Rasters
Game Programming - Episode 7 - Buffered Image and Rasters
The Cherno
49 Game Programming - Episode 8 - The Screen Class
Game Programming - Episode 8 - The Screen Class
The Cherno
50 Game Programming - Episode 9 - Rendering Pixels
Game Programming - Episode 9 - Rendering Pixels
The Cherno
51 Game Programming - Episode 10 - Clearing the Screen
Game Programming - Episode 10 - Clearing the Screen
The Cherno
52 Game Programming - Episode 11 - "Out of Bounds, Baby!"
Game Programming - Episode 11 - "Out of Bounds, Baby!"
The Cherno
53 Game Programming - Episode 12 - Negative Bounds
Game Programming - Episode 12 - Negative Bounds
The Cherno
54 Game Programming - Episode 13 - Timer
Game Programming - Episode 13 - Timer
The Cherno
55 Game Programming - Episode 14 - FPS Counter
Game Programming - Episode 14 - FPS Counter
The Cherno
56 Episode 15 - Tiles
Episode 15 - Tiles
The Cherno
57 Game Programming - Episode 16 - The Map
Game Programming - Episode 16 - The Map
The Cherno
58 The Walls 2 - Minecraft PvP Survival Map
The Walls 2 - Minecraft PvP Survival Map
The Cherno
59 Game Programming - Episode 17 - Key Input
Game Programming - Episode 17 - Key Input
The Cherno
60 Game Programming - Episode 18 - Controlling The Map
Game Programming - Episode 18 - Controlling The Map
The Cherno

The video teaches how to use the static keyword in C++ to extend the lifetime of variables and create Singleton classes. It demonstrates the behavior of static variables in local scope and their application in persisting variables between function calls. By watching this video, viewers can learn how to apply the static keyword in their own C++ programs.

Key Takeaways
  1. Create a function and declare a static variable inside it
  2. Call the function multiple times to test the behavior of the static variable
  3. Print the value of the static variable each time the function is called
  4. Increment the static variable each time the function is called
  5. Test the behavior of the static variable with and without the static keyword
  6. Declare static in a local scope to create a variable that persists between function calls
  7. Use static to create a Singleton class with a single instance
💡 Using static in a local scope can extend the lifetime of an object to be essentially forever, and returning a reference to a static object can prevent its destruction.
Up next
George Hotz | Programming | tinygrad, starting on CLOUD=1 | Part 2
george hotz archive
Watch →