Assigning Values to Variables

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.

To assign values to variables

1.
Open var1.c (Script 2.1) in your text editor or IDE.

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.
Save the file as var2.c.

4.
Compile the application (Figure 2.2).

Figure 2.2. Compiling var2.c using the command-line gcc tool.


✓ 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.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset