This lesson explains what scope is, and how you can use it to your advantage in your projects.

Transcript

The straightforward way to think about Scope is that code inside braces or curly brackets can access variables in the same level or outside that. But, you can't access variables if you have to go into curly brackets. For instance, I've created what's called a global variable which means it's declared outside any function, it can then be used inside any function because it would be outside the set of braces. It couldn't go the other way through and access anything that was inside the function like these local variables now you need to be careful with global variables because they can also be changed by any function. If, however you create a local variable that is the same name as a global variable, it will effectively overwrite the link and use the local one instead. Now if we move down these variables here are called parameters and they're treated as if they are local variables to that function. Anytime a function ends it deletes the local variables unless they have static at the beginning, which will maintain them the next time the function is run.

So, as you can see here the first time the function is run the value is seven, it's then increased and then the next time the function is run its value is eight. Again, if you have a local variable that is the same name as a global variable it will use that instead and the same can be said for parameters. For instance, this parameter here has the same name as the global variable and it will use that in step and further down is an example of what I was saying before. This variable here is only declared inside main which means the function is unable to access it. It should also be noted that because the function ends and deletes all its variables and parameters, this won't send any data back to main. There are exceptions to this, but we'll be covering those in another chapter.

Have a look at the code that I put on the workshop page and follow through if you have any questions put them up on the forum and I'd be happy to answer them for you this is the end of chapter 2 and I'll see you in the next one.

Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.