Variables
Table of Contents
WIP: ChatGPT converted this from my LaTeX document to orgmode so I still need to review this.
\begin{center} \includegraphics[width=\textwidth]{Basics/images/variables} \end{center}
We use variables in programming as places to temporarily store data so that we can manipulate that data. We can have the user write to it via the keyboard, we can use files to write data to variables, we can do math operations or modify these variables, and we can print them back out to the screen or a text file.\footnote{Printing here meaning ``display on the screen''; not to a printer. Holdover from ancient times when computers' outputs came via the printers.}
When we're writing programs in C++, we need to tell our program what the data type of each variable is, and give each variable a variable name (aka identifier). When a variable is declared, a space in RAM is allocated to that variable and it can store its data there. That data can be manipulated or overwritten later as needed in the program.
1. Data types
In C++, when we want to create a variable we need to tell the compiler what the data type of the variable is. Data types specify what is stored in the variable (whole numbers? numbers with decimal values? text? true/false values?). Each data type takes up a different amount of space in memory.
\begin{longtable}{|l|p{4cm}|l|l|} \hline \textbf{Data type} & \textbf{Values} & \textbf{Size} & \textbf{Example code} \\ \hline \endfirsthead \multicolumn{4}{l}{{\em (Continued from previous page)}} \\ \hline \textbf{Data type} & \textbf{Values} & \textbf{Size} & \textbf{Example code} \\ \hline \endhead \hline \multicolumn{4}{r}{{\em (Continued on next page)}} \\ \endfoot \hline \endlastfoot integer & whole numbers & 4 bytes & \texttt{int age = 100; } \\ \hline char & single symbols - letters, numbers, anything & 1 byte & \texttt{char currency = '\$';} \\ \hline float & numbers with decimals & 4 bytes & \texttt{float price = 9.95;} \\ \hline double & numbers with decimals & 8 bytes & \texttt{double price = 1.95;} \\ \hline string & any text, numbers, symbols, any length & variable & \texttt{string password = "123secure";} \\ \hline boolean & \texttt{true} or \texttt{false} & 1 byte & \texttt{bool saved = false;} \\ \hline \end{longtable}
Of these, notice that the string data type doesn't have a fixed size. This is because technically, behind-the-scenes, a string is really just an array (or list) of char data types. The C++ standard library contains a string library that handles a lot of text-related functionality like find.
Floats and doubles both store numbers with fractional (decimal) parts, but a double takes up double the memory in RAM, allowing to store more accurate fractional amounts. A float has 6 to 9 digits of precision and a double has 15 to 18 digits of precision.\footnote{From https://www.learncpp.com/cpp-tutorial/floating-point-numbers/}
Boolean data types store true and false values, but will also accept integer values when assigned. It will convert a value of 0 to false and any other number to true.
2. Declaring variables and assigning values to variables
Variable declaration
When we're declaring a variable, it needs to follow one of these formats:
- \texttt{DATATYPE VARIABLENAME;}
- \texttt{DATATYPE VARIABLENAME = VALUE;}
- \texttt{DATATYPE VARIABLENAME1, VARIABLENAME2, VARIABLENAME3;}
- \texttt{DATATYPE VARIABLENAME1 = VALUE1, VARIABLENAME2 = VALUE2;}
The data type goes first, then the variable name/identifier, and if you'd like, you can also assign a value during the same step (though this is not required).
Once a variable has been declared, you don't need to declare it again. This means you don't need to re-specify its data type when you're using it. Just address the variable by its name, and that's all.
Code that uses integers to figure out how many candies each kid should get:
// Declaring variables and assigning values int totalCandies = 10; int totalKids = 5; int candiesPerKid = totalCandies / totalKids; // Reusing the same variables later on totalCandies = 100; totalKids = 10; candiesPerKid = totalCandies / totalKids;
Code to display the price plus tax to the user:
float price = 9.99; float tax = 0.11; // Text output to the screen. Can do math within! cout << "Please pay " << (price + price * tax);
Variable assignment
- \texttt{VARIABLENAME = LITERAL;} - Stores the LITERAL value in VARIABLENAME.
- \texttt{VARIABLENAME1 = VARIABLENAME2;} - Copies the value from VARIABLENAME2 to VARIABLENAME1.
When assigning a value to a variable, the variable being assigned to always goes on the left-hand side (LHS) of the equal sign =. The = sign is known here as the assignment operator.
The item on the right-hand side (RHS) will be the value stored in the variable specified on the LHS. This can be a literal (a hard-coded value) or it can be a different variable of the same data type, whose value you want to copy over.
Assigning literal values to variables:
```cpp
price = 9.99; / 9.99 is a float literal
state = "Kansas"; / "Kansas" is a string literal
operation = ''; // '' is a char literal
Copying student13's value to the bestStudent variable:
cpp
bestStudent = student13;
Assignment
Naming conventions
You can name a variable anything you'd like, but it can only contain numbers, underscore (_), and upper- and lower-case letters in the name. Variable names can begin with the underscore or a letter, but they cannot start with a number. And definitely NO spaces are allowed in a variable name!
Additionally, a variable name cannot be a keyword in C++, a name reserved for something else in the language, such as void, if, int, etc.
Everything in C++ is case sensitive, which means if you name a variable username, it will be a different variable from one named userName (or if you type "userName" when the variable is called "username," the compiler will complain at you because it doesn't know what you mean).
In C++, it's standard to name your variables using camel casing, with a lowercase first letter. This means that if your variable name "should" contain spaces, you just capitalize the next word instead:
cpp
int howManyCookies; string mySecurePassword; float howMuchStudentLoansIHave;
Unsigned data types
Sometimes it doesn't make sense to store negative values in a variable - such as speed (which isn't directional, like velocity), the size of a list (can't have negative items), or measurement (can't have negative width). You can mark a variable as unsigned to essentially double its range (by getting rid of the negative side of values). For instance, a normal int can store values from -2,147,483,648 to 2,147,483,647, but if you mark it as unsigned, then your range is 0 to 4,294,967,295.
Modern C++: \texttt{auto}
In C++11 and later, you can use the keyword \texttt{auto} as the "data type" in your variable declaration that includes an assignment statement. When you use \texttt{auto}, it uses the assigned value to automatically figure out the variable's data type, so you don't have to explicitly define it:
cpp
auto price = 9.99; / it's a double! auto price2 = 2.95f; / it's a float! auto player = '@'; / it's a char! auto amount = 20; / it's an int!
Auto
Basic operations on variables
Now that you have variables available in your program to play with, what can you even do with them?
Outputting variable values
Using the cout (console-out) statement, you can display text to the screen with string literals:
cpp
cout << "Hello, world!" << endl;
But you can also display the values stored within variables, simply by using the variable's name:
cpp
cout << myUsername << endl;
(We will cover more about input and output next part)
Inputting variable values
We can use the cin (console-in) statement to get the user to enter something on the keyboard and store that data into a variable:
cpp
cin >> favoriteColor;
Math operations
With variables with numeric data types (ints, floats, doubles), we can do arithmetic with the +, -, *, and / operators.
cpp
cout << "Sum: " << num1 + num2 + num3 << endl;
Operations:
Addition (+) Subtraction (-) Multiplication (*) Division (/)
Make sure to put the result somewhere!
When you do a math operation and you want to use the result elsewhere in the program, make sure you're storing the result in a variable via an assignment statement! If you just do this, nothing will happen:
cpp
totalCats + 1;
You can use an assignment statement to store the result in a new variable:
cpp
newCatTotal = totalCats + 1;
Or overwrite the variable you're working with:
cpp
totalCats = totalCats + 1;
Cats
Compound operations:
There are also shortcut operations you can use to quickly do some math and overwrite the original variable. This works with each of the arithmetic operations:
cpp
// Long way: totalCats = totalCats + 5;
// Compound operation: totalCats += 5;
String operations
Strings have some special operations you can do on them. You can also see a list of functions supported by strings here: C++ String Reference (We will cover more with strings in a later part).
Concatenating strings:
You can use the + symbol to combine strings together. When used in this context, the + sign is called the concatenation operator.
cpp
string type = "pepperoni"; string food = "pizza";
// Creates the string "pepperoni pizza" string order = type + " " + food;
Letter-of-the-string:
You can also use the subscript operator [ ] (more on this when we cover arrays) to access a letter at some position in the string. Note that in C++, the position starts at 0, not 1.
cpp
string food = "pizza";
char letter1 = food[0]; / Stores 'p' char letter2 = food[1]; / Stores 'i' char letter3 = food[2]; / Stores 'z' char letter4 = food[3]; / Stores 'z' char letter5 = food[4]; // Stores 'a'
Named constants
Whenever you find yourself using a literal value in your assignment statements, you may want to think about whether you should replace it with a named constant instead.
A named constant looks like a variable when you declare it, but it also has the keyword const - meaning that the value can't change after its declaration.
Named constant declaration format:
\texttt{const CONSTNAME = LITERAL;} - Stores the LITERAL value in CONSTNAME.
Let's say you wrote a program and hard-coded the tax rate:
cpp
// Somewhere in the code… checkoutPrice = cartTotal + ( cartTotal * 0.0948 );
// Somewhere else in the code… cout << 0.0948 << " sales tax" << endl;
Then the tax rate changes later on. You would have to go into your program and search for "0.0948" and update all those places!
Instead, it would have been easier to assign the tax rate ONCE to a named constant and referred to that instead:
cpp
// Beginning of program somewhere… const SALESTAX = 0.0948;
// Somewhere in the code… checkoutPrice = cartTotal + ( cartTotal * SALESTAX );
// Somewhere else in the code… cout << SALESTAX << " sales tax" << endl;
If you ever find yourself using the same literal multiple times in your program, then perhaps consider replacing it with a named constant.
Named constant naming convention:
In C++, it is customary to give your named constants names in ALL CAPS, using underscores (_) to separate words.
vbnet
Here's the converted text in Org Mode:
```org
We use variables in programming as places to temporarily store data so that we can manipulate that data. We can have the user write to it via the keyboard, we can use files to write data to variables, we can do math operations or modify these variables, and we can print them back out to the screen or a text file.#+footnote: Printing here meaning "display on the screen"; not to a printer. Holdover from ancient times when computers' outputs came via the printers.
When we're writing programs in C++, we need to tell our program what the data type of each variable is, and give each variable a variable name (aka identifier). When a variable is declared, a space in RAM is allocated to that variable and it can store its data there. That data can be manipulated or overwritten later as needed in the program.
Data types
In C++, when we want to create a variable we need to tell the compiler what the data type of the variable is. Data types specify what is stored in the variable (whole numbers? numbers with decimal values? text? true/false values?). Each data type take up a different amount of space in memory.
Data type | Values | Size | Example code |
---|---|---|---|
integer | whole numbers | 4 bytes | int age = 100; |
char | single symbols - letters, numbers, anything | 1 byte | char currency = '$'; |
float | numbers w/ decimals | 4 bytes | float price = 9.95; |
double | numbers w/ decimals | 8 bytes | double price = 1.95; |
string | any text, numbers, symbols, any length | variable | string password = "123secure"; |
boolean | true or false | 1 byte | bool saved = false; |
Of these, notice that the string data type doesn't have a fixed size. This is because technically, behind-the-scenes, a string is really just an array (or list) of char data types. The C++ standard library contains a string library that handles a lot of text-related functionality like find.
Floats and doubles both store numbers with fractional (decimal) parts, but a double takes up double the memory in RAM, allowing to store more accurate fractional amounts. A float has 6 to 9 digits of precision and a double has 15 to 18 digits of precision.
Boolean data types store true and false values, but will also accept integer values when assigned. It will convert a value of 0 to false and any other number to true.
Declaring variables and assigning values to variables
Variable declaration
When we're declaring a variable it needs to follow one of these formats:
- DATATYPE VARIABLENAME;
- DATATYPE VARIABLENAME = VALUE;
- DATATYPE VARIABLENAME1, VARIABLENAME2, VARIABLENAME3;
- DATATYPE VARIABLENAME1 = VALUE1, VARIABLENAME2 = VALUE2;
The data type goes first, then the variable name/identifier, and if you'd like, you can also assign a value during the same step (though this is not required). Once a variable has been declared, you don't need to declare it again. This means you don't need to re-specify its data type when you're using it. Just address the variable by its name and that's all.
Code that uses integers to figure out how many candies each kid should get:
```cpp // Declaring variables and assigning values int totalCandies = 10; int totalKids = 5; int candiesPerKid = totalCandies / totalKids;
// Reusing the same variables later on totalCandies = 100; totalKids = 10; candiesPerKid = totalCandies / totalKids;
Code to display the price plus tax to the user:
cpp
float price = 9.99; float tax = 0.11; // Text output to the screen. Can do math within! cout << "Please pay " << (price + price * tax);
Variable assignment
VARIABLENAME = LITERAL; ~\ Stores the LITERAL value in VARIABLENAME. VARIABLENAME1 = VARIABLENAME2; ~\ Copies the value from VARIABLENAME2 to VARIABLENAME1.
When assigning a value to a variable, the variable being assigned to always goes on the left-hand side (``LHS'') of the equal sign =. The = sign is known here as the assignment operator.
The item on the right-hand side (``RHS'') will be the value stored in the variable specified on the LHS. This can be a literal (a hard-coded value), or it can be a different variable of the same data type, whose value you want to copy over.
Assigning literal values to variables:
cpp
price = 9.99; / 9.99 is a float literal
state = "Kansas"; / "Kansas" is a string literal
operation = ''; // '' is a char literal
Copying student13's value to the bestStudent variable:
cpp
bestStudent = student13;
Naming conventions
You can name a variable anything you'd like - but it can only contain numbers, underscore (_), and upper- and lower-case letters in the name. Variable names can begin with the underscore or a letter, but it cannot start with a number. And definitely NO spaces allowed in a variable name!
Additionally, a variable name cannot be a keyword in C++ - a name reserved for something else in the language, such as void, if, int, etc.
Everything in C++ is case sensitive as well, which means if you name a variable username, it will be a different variable from one named userName (or if you type "userName" when the variable is called "username", the compiler will complain at you because it doesn't know what you mean).
In C++, it's standard to name your variables using camel casing, with a lower-case first letter. This means that if your variable name "should" contain spaces, you just capitalize the next word instead:
cpp
int howManyCookies; string mySecure