In this chapter, we talked about local variables that only exist while a function is running. There are also variables that can be accessed from any function at any time. We call these global variables. To make a variable global, you declare it outside of a particular function. For example, you could add a lastTemperature variable that holds the temperature that was converted from Celsius. Add a global variable to the program:
#include <stdio.h> #include <stdlib.h> // Declare a global variable float lastTemperature; float fahrenheitFromCelsius(float cel) { lastTemperature = cel; float fahr = cel * 1.8 + 32.0; printf("%f Celsius is %f Fahrenheitn", cel, fahr); return fahr; } int main(int argc, const char * argv[]) { float freezeInC = 0; float freezeInF = fahrenheitFromCelsius(freezeInC); printf("Water freezes at %f degrees Fahrenheitn", freezeInF); printf("The last temperature converted was %fn", lastTemperature); return EXIT_SUCCESS; }
Any complex program will involve dozens of files containing different functions. Global variables are available to the code in every one of those files. Sometimes sharing a variable between different files is what you want. But, as you can imagine, having a variable that can be accessed by multiple functions can also lead to great confusion. To deal with this, we have static variables. A static variable is like a global variable in that it is declared outside of any function. However, a static variable is only accessible from the code in the file where it was declared. So you get the non-local, “exists outside of any function” benefit while avoiding the “you touched my variable!” issue.
You can change your global variable to a static variable, but because you have only one file, main.c, it will have no effect whatsoever.
// Declare a static variable static float lastTemperature;
Both static and global variables can be given an initial value when they are created:
// Initialize lastTemperature to 50 degrees static float lastTemperature = 50.0;
If you don’t give them an initial value, they are automatically initialized to zero.
In this chapter, you have learned about functions. When we get to Objective-C in Part III, you will hear the word method – a method is very, very similar to a function.