Continuing with the recipe metaphor from the last chapter, sometimes a chef will keep a small blackboard in the kitchen for storing data. For example, when unpacking a turkey, he notices a label that says “14.2 Pounds.” Before he throws the wrapper away, he will scribble “weight = 14.2” on the blackboard. Then, just before he puts the turkey in the oven, he will calculate the cooking time (15 minutes + 15 minutes per pound) by referring to the weight on the blackboard.
During execution, a program often needs places to store data that will be used later. A place where one piece of data can go is known as a variable. Each variable has a name (like cookingTime) and a type (like a number). In addition, when the program executes, the variable will have a value (like 228.0).
In a program, you create a new variable by declaring its type and name. Here’s an example of a variable declaration:
float weight;
The type of this variable is float, and its name is weight. At this point, the variable doesn’t have a value.
In C, you must declare the type of each variable for two reasons:
The type lets the compiler check your work for you and alert you to possible mistakes or problems. For instance, say you have a variable of a type that holds text. If you ask for its logarithm, the compiler will tell you something like “It doesn’t make any sense to ask for this variable’s logarithm.”
The type tells the compiler how much space in memory (how many bytes) to reserve for that variable.
Here is an overview of the commonly used types. We will return in more detail to each type in later chapters.
These are the types that a C programmer uses every day. It is quite astonishing what complex ideas can be captured in these five simple ideas.