Week 2: C++ Data Fundamentals & Operations

Learn how to store data using variables, understand basic types, and perform operations.

Explore Chapter 2

Chapter 2: Variables, Data Types, and Operators

Variables: Naming, Declaration, Initialization.

Variables are named storage locations in memory used to hold data. Before using a variable in C++, you must declare it, specifying its data type and name.

Naming Variables

C++ variable names (identifiers):

  • Must begin with a letter (a-z, A-Z) or an underscore (_).
  • Can contain letters, numbers, and underscores.
  • Are case-sensitive (`myVariable` and `myvariable` are different).
  • Cannot be C++ keywords (like `int`, `if`, `class`, `return`, etc.).
  • Convention often uses `camelCase` or `snake_case`. Be consistent!

Declaration

Declaring a variable tells the compiler its type and name.

int studentCount;     // Declares an integer variable named studentCount
double averageScore;    // Declares a double-precision floating-point variable
char grade;           // Declares a character variable
bool isValid;         // Declares a boolean variable

Initialization

Initialization means assigning an initial value to a variable at the time of declaration. It's good practice to initialize variables to avoid using potentially undefined values.

int age = 25;               // C-like initialization
double pi(3.14159);        // Constructor initialization
char initial {'A'};          // Uniform initialization (preferred in modern C++)
bool isReady = true;

Assignment

You can change the value of a variable (unless it's `const`) after declaration using the assignment operator `=`.

studentCount = 30;    // Assign 30 to studentCount
age = 26;             // Update the value of age

Fundamental Data Types.

C++ is statically typed, meaning the type of a variable is fixed at compile time. Here are some fundamental types:

  • Integer Types: Store whole numbers.
    • `int`: The most common integer type (size depends on the system, often 4 bytes).
    • `short int` (or `short`): Usually smaller than `int`.
    • `long int` (or `long`): Usually larger than or equal to `int`.
    • `long long int` (or `long long`): Usually larger than `long`.
    • Modifiers: `signed` (can hold +/- values, default) and `unsigned` (holds only non-negative values, allowing for a larger positive range).
    int score = 100;
    unsigned int positiveValue = 50000;
  • Floating-Point Types: Store real numbers (numbers with decimal points).
    • `float`: Single-precision floating-point.
    • `double`: Double-precision floating-point (more precision than `float`, generally preferred).
    • `long double`: Extended-precision floating-point (even more precision).
    float price = 19.99f; // 'f' suffix denotes float literal
    double measurement = 123.45678;
  • Character Type:
    • `char`: Stores a single character (letter, digit, symbol). Enclosed in single quotes `' '`. It's technically an integer type storing the character's ASCII/Unicode value.
    char grade = 'A';
    char symbol = '#';
  • Boolean Type:
    • `bool`: Stores logical values `true` or `false`.
    bool isActive = true;
    bool hasFinished = false;
  • Void Type:
    • `void`: Represents the absence of a type. Used primarily for functions that do not return a value or for generic pointers.

The `sizeof` operator can tell you the size (in bytes) of a data type or variable on your specific system.

std::cout << "Size of int: " << sizeof(int) << " bytes" << std::endl;

Constants (`const`).

Constants are variables whose values cannot be changed after initialization. They make code safer and more readable by representing fixed values.

You declare a constant using the `const` keyword.

const double PI = 3.14159;
const int MAX_USERS = 100;

// PI = 3.14; // Error! Cannot assign to a const variable.
// MAX_USERS++; // Error!

It's a common convention to name constants using all uppercase letters.

Operators in C++.

Operators are symbols that perform operations on operands (variables or values).

Arithmetic Operators

Perform mathematical calculations.

  • `+` (Addition), `-` (Subtraction), `*` (Multiplication), `/` (Division), `%` (Modulo - remainder)
int a = 10, b = 3;
int sum = a + b; // 13
int diff = a - b; // 7
int product = a * b; // 30
int quotient = a / b; // 3 (integer division truncates)
int remainder = a % b; // 1
double preciseQuotient = (double)a / b; // 3.333... (requires casting for float division)

Comparison (Relational) Operators

Compare two values, resulting in `true` or `false`.

  • `==` (Equal to), `!=` (Not equal to), `>` (Greater than), `<` (Less than), `>=` (Greater than or equal to), `<=` (Less than or equal to)
bool isEqual = (a == 10); // true
bool isGreater = (a > b); // true

Logical Operators

Combine or modify boolean expressions.

  • `&&` (Logical AND), `||` (Logical OR), `!` (Logical NOT)
bool condition1 = true;
bool condition2 = false;
bool bothTrue = condition1 && condition2; // false
bool eitherTrue = condition1 || condition2; // true
bool notCondition1 = !condition1;     // false

Assignment Operators

Assign values to variables.

  • `=` (Assignment), `+=`, `-=`, `*=`, `/=`, `%=` (Compound assignment)
int count = 5;
count += 3; // Equivalent to count = count + 3; (count is now 8)
count *= 2; // Equivalent to count = count * 2; (count is now 16)

Increment/Decrement Operators

  • `++` (Increment), `--` (Decrement) - Can be prefix (`++x`) or postfix (`x++`).
int num = 10;
num++;    // num becomes 11 (postfix)
++num;    // num becomes 12 (prefix)
--num;    // num becomes 11 (prefix)

Understanding operator precedence (the order in which operators are evaluated) is important. Use parentheses `()` to enforce a specific order when needed.

Type Casting.

Type casting is the explicit conversion of a value from one data type to another.

C-style Cast

int total = 10;
int count = 3;
double average = (double)total / count; // Cast 'total' to double before division
                                            // Result: 3.333...

Static Cast (C++)

The preferred method in modern C++ for many standard type conversions.

double average_cpp = static_cast<double>(total) / count;

Be cautious with type casting, especially narrowing conversions (e.g., `double` to `int`), as they can lead to loss of information.

Syllabus