Overview
This lecture introduces variables in C++, explaining how to declare and assign them, and reviews key data types with examples.
Variable Basics
- A variable represents a value and must be declared and assigned before use.
- Declaration specifies the data type and gives the variable a unique name (e.g.,
int x;).
- Assignment gives the variable a value (e.g.,
x = 5;).
- Declaration and assignment can be combined (e.g.,
int x = 5;).
- Variables behave as if they hold their assigned value when used in expressions.
Displaying Variables
- Use
std::cout to display variable values in C++.
- You can show variables with text using string literals and concatenation.
Data Types in C++
int stores whole numbers (e.g., age, year, days).
- Assigning a decimal to
int truncates the decimal (e.g., 7.5 becomes 7).
double stores numbers with decimals (e.g., price, GPA, temperature).
char stores a single character using single quotes (e.g., grade, initial, currency symbol).
- Assigning more than one character to
char leads to errors or truncation.
bool (boolean) stores either true or false (e.g., isStudent, isPoweredOn, forSale).
string stores sequences of text using double quotes (e.g., names, days, addresses).
Examples
int sum = x + y; stores the result of adding two integers.
double price = 10.99; stores a price with cents.
char grade = 'A'; stores a letter grade.
bool student = true; indicates if someone is a student.
std::string name = "Bro"; stores a name.
Key Terms & Definitions
- Variable — a named storage for a value.
- Declaration — defining the variable's type and name.
- Assignment — giving a value to a variable.
- int — stores whole numbers.
- double — stores numbers with decimal points.
- char — stores a single character.
- bool — stores true or false.
- string — stores sequences of text.
Action Items / Next Steps
- Post in the comments: one integer, one double, one character, one boolean, and one string variable with your own example values.