Slightly More Complex Issues

For most simple programs, nothing more than the elements discussed so far are needed. But some additional information can make hard problems simple.

The first thing we will discuss is called scope. This is the concept that variables have a lifetime, and that corresponds to where they are in the program.

If a variable is declared outside of a function, it is said to have global scope. That means that all functions after the variable is declared can see and use that variable.

If a variable is declared inside a function (or as a parameter to the function), it has function scope. It is only known inside that one function. If another function declares a variable with the same name, it is a new and entirely separate variable.

The space that variables in function scope occupy is released when the function returns, and that space can then be used by other functions for their own variables. This is important when you have a lot of data in your program, and your microprocessor chip only has 512 bytes of data to use for everything.

You can also declare variables inside any block of statements enclosed in curly braces. When the program leaves that block, the space is reclaimed, just as if a function had returned.

Inside a for statement, you can declare the variable used to do the counting. The scope of that variable is the for statement, and the block or statement the for controls. This is handy for simple variables you just use for counting, such as i or x.

If you want to prevent a variable from being reclaimed when it goes out of scope, you can declare it static. A static variable keeps its value across function calls of block exits.