Once you've declared a variable, you can initialize it, which means giving that variable a value. Assigning values to simple variables like numbers is very easy and requires only the assignment operator (=):
int model_year; model_year = 2004; float cost; cost = 1.95;
Although you must declare a variable before assigning a value to it, C does allow you to perform both acts in one step:
int model_year = 2004; float cost = 1.95
Let's build on the previous example by assigning values to the declared variables.
1. | |
2. | After declaring the variables but before the return statement, assign each variable a value (Script 2.2): age = 40; hourly_wage = 3.35; Script 2.2. Now each variable has been assigned a value, corresponding to its type.Obviously you can insert any value you want here, as long as it matches the variable's type. This means that integers don't have decimals or fractions and that floats must use a decimal point. As with all numbers, you must not use quotation marks when assigning these values. |
3. | |
4. |
✓ Tips
One of the strengths of C is that you must declare every variable before you use it. Because of this, compilers will catch errors, such as referring to a variable by the wrong name.
Some debuggers and IDEs have the capability to show you, on a line-by-line basis, the values of every variable in your file. You'll learn a little about debugging tools in Appendix A.