I l @ ve RuBoard |
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.
int apples = 3; /* RIGHT */ int oranges = 3.0; /* WRONG */
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, as 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.
I l @ ve RuBoard |