firstLetter = 'a'; // give firstLetter the value 'a'
hour = 11; // assign the value 11 to hour
minute = 59; // set minute to 59
This example shows three assignments, and the comments show three different ways people sometimes talk about assignment statements. The vocabulary can be confusing here, but the idea is straightforward:
A common way to represent variables on paper is to draw a box with the name of the variable on the outside and the value of the variable on the inside. This kind of figure is called a state diagram because is shows what state each of the variables is in (you can think of it as the variableβs βstate of mindβ). This diagram shows the effect of the three assignment statements:
I sometimes use different shapes to indicate different variable types. These shapes should help remind you that one of the rules in C++ is that a variable has to have the same type as the value you assign it.
It can be useful to examine the βstate of mindβ of the computer as it runs code you have written. Programmers use debuggers to do so. In this book, you can use the codelens feature to run programs line by line.
Run the code sample below by using the Next button to advance line by line. As you do so, watch the area to the right to examine the βstate of mindβ of the computer as it runs the code.
This rule is sometimes a source of confusion, because there are many ways that you can convert values from one type to another, and C++ sometimes converts things automatically. But for now you should remember that as a general rule variables and values have the same type, and weβll talk about special cases later.
Another source of confusion is that some strings look like integers, but they are not. For example, the string β123β, which is made up of the characters 1, 2 and 3, is not the same thing as the number 123. This assignment is illegal:
You love your car, and you decide to keep track of its make, model, and year. You do so using three assignment statements IN THAT ORDER. For the sake of this problem, suppose you drive a 2001 Jeep Cherokee. Hint: there are a couple ways to write an assignment statement.
string make;
make = "Jeep";
---
string make = Jeep; #paired
---
make = "Jeep;"
---
string model = "Cherokee";
---
string model;
model = Cherokee; #paired
---
string model = Cherokee;
---
int year = 2001;
---
int year;
2001 = year; #paired
---
int year;
year = 2001