Using Data Types
When you develop a program, note the variables you need and which type they should be. Most likely, you can use int or possibly float for the numbers and char for the characters. Declare them at the beginning of the function that uses them. Choose a name for the variable that suggests its meaning. When you initialize a variable, match the constant type to the variable type. Here’s an example:
int apples = 3; /* RIGHT */ int oranges = 3.0; /* POOR FORM */
C is more forgiving about type mismatches than, say, Pascal. C compilers allow the second initialization, but they might complain, particularly if you have activated a higher warning level. It is best not to develop sloppy habits.
When you initialize a variable of one numeric type to a value of a different type, C converts the value to match the variable. This means you may lose some data. For example, consider the following initializations:
int cost = 12.99; /* initializing an int to a double */ float pi = 3.1415926536; /* initializing a float to a double */
The first declaration assigns 12 to cost; when converting floating-point values to integers, C simply throws away the decimal part (truncation) instead of rounding. The second declaration loses some precision, because a float is guaranteed to represent only the first six digits accurately. Compilers may issue a warning (but don’t have to) if you make such initializations. You might have run into this when compiling Listing 3.1.
Many programmers and organizations have systematic conventions for assigning variable names in which the name indicates the type of variable. For example, you could use an i_ prefix to indicate type int and us_ to indicate unsigned short, so i_smart would be instantly recognizable as a type int variable and us_verysmart would be an unsigned short variable.