Variables and declarations
Storing data. Discriminating types. Declaring data.
Variable names in C follow the same rules as function names, as far as what characters they can contain. (See Function names.) Variables work differently from functions, however. Every variable in C has a data type, or type, that conveys to the the compiler what sort of data will be stored in it. Functions in C are sometimes said to have types, but a function's type is actually the data type of the variable it returns.
In some older computer languages like BASIC, and even some newer ones
like Perl, you can tell what type a variable is because its name begins
or ends with a special character. For example, in many versions of
BASIC, all integer variable names end with a percent sign (
YEAR%. No such convention exists in C. Instead, we
declare variables, or tell the compiler that they are of a certain type,
before they are used. This feature of C has the following advantages
- It gives a compiler precise information about the amount of memory that will have to be allotted to a variable when a program is run, and what sort of arithmetic will have to be used with it (e.g. integer, floating point, or none at all).
- It provides the compiler with a list of the variables so that it can catch errors in the code, such as assigning a string to an integer variable.
There are a lot of variable types in C. In fact, you can define your own, but there are some basic types ready for use. We will discuss them in the following sections.