Learn C++ · 2/15

C++ Fundamentals: The Building Blocks

9 min read

Welcome to the foundation! If programming were construction, the previous section was buying the land and getting the permits (setup). Now, we are pouring the concrete.

In this module, we are going to look at how C++ remembers things, how it does math, and how it talks to you. We will focus on modern C++ standards because, let's be honest, nobody wants to code like it's 1998 anymore.


1. Variables and Data Types: Storing Your Data 💾

The Problem

Imagine you are a chef. You chop an onion. Where do you put it? You can't just hold it in your hand while chopping the carrots; you need a bowl. In computing, if you calculate a number or accept a user's name, you need a place to put it in the memory (RAM) so you can use it later.

The Solution: Variables

A variable is a named storage location in the computer's memory that holds a value.

Data Types: The Shape of the Container

Before you create a variable, C++ needs to know what kind of data goes in it. You cannot put soup in a colander. C++ is a strongly typed language, meaning if you say a box holds shoes, you cannot try to stuff a giraffe into it later.

Here are the industry-standard types you will use 99% of the time:

Type Description Size (usually) Example
int Whole numbers (integers). 4 bytes 42, -7
double Decimal numbers (floating point). 8 bytes 3.14, 0.005
char A single character. 1 byte 'a', 'Z'
bool True or False logic. 1 byte true, false
std::string Text (a sequence of chars). Dynamic "Hello World"

Note: There are other types like float, short, and long long, but in modern general-purpose C++, int and double are your bread and butter for numbers.

How to Declare and Initialize

In the old days, we did this:

cpp
int age = 25; // C-style initialization

In Modern C++ (C++11 and later), we prefer Brace Initialization.
Why? Because it forbids "narrowing conversions" (accidentally shoving a decimal into an integer variable and losing data).

cpp
#include <iostream>
#include <string>

int main() {
    // 1. Declaration and Initialization
    int lives{3};            // Good: Clear and safe
    double health{95.5};     // Precision matters
    char rank{'A'};          // Note the single quotes for char
    bool isAlive{true};      // Boolean logic
    std::string name{"Hero"}; // Note double quotes for string
    
    // 2. The Danger Zone (Uninitialized Variables)
    int badVariable; 
    // If you print badVariable now, you might get 0, or you might get 32767. 
    // It grabs whatever garbage data was sitting in that RAM address previously.
    // ALWAYS initialize your variables!
    
    std::cout << name << " has " << lives << " lives left." << std::endl;
    
    return 0;
}

🔍 Under the Hood

When you write int a{5};, the OS finds a 4-byte block of memory (RAM), marks it as "reserved" for your program, and writes the binary representation of 5 (0000...0101) into that block. The variable name a is just a human-readable label for that memory address (e.g., 0x7fff5694).


2. Constants and Auto: Modern Value Management 🛡️

The Problem (Constants)

You are writing a program to calculate the area of a circle. You type 3.14 in five different places. Later, your boss (or physics teacher) says, "We need more precision! Use 3.14159!" Now you have to find and change it in five places. Also, what if you accidentally write PI = 5 later in the code? The universe breaks.

The Solution: const

The const keyword promises the compiler that this variable cannot be changed after it is created. It is "read-only".

cpp
const double pi{3.14159};
int radius{5};

// pi = 3.14; // ❌ ERROR: Compiler will scream at you. This is good.

The Problem (Auto)

C++ types can get really long and scary. Imagine having to type this:
std::vector<std::map<std::string, int>>::iterator it = myData.begin();
That is a recipe for Carpal Tunnel Syndrome.

The Solution: auto

The auto keyword tells the compiler: "Look at the value on the right side of the = sign and figure out the type yourself." This is called Type Deduction.

cpp
auto score{100};      // Compiler sees 100 (int), so 'score' becomes int
auto price{19.99};    // Compiler sees double, 'price' becomes double
auto greeting{"Hi"};  // Compiler deduces const char* (be careful with strings!)

Industry Standard: Use auto when the type is obvious (like auto i = variable_with_long_type_name) or redundant. Do not use auto for simple things like auto x = 5; because it makes the code harder to read for humans. We want to know x is an int without guessing.


3. Operators: Doing Math, Logic, and Comparisons 🧮

The Problem

Data that just sits there is boring. We need to manipulate it, change it, and check it.

The Solution: Operators

Operators are symbols that tell the compiler to perform specific mathematical or logical manipulations.

Arithmetic Operators

Standard math rules apply.

  • + (Add), - (Subtract), * (Multiply), / (Divide)
  • % (Modulus): Returns the remainder of a division.

⚠️ The Integer Division Trap:
This is the most common bug for beginners.

cpp
int a{5};
int b{2};
double result = a / b; 
// You expect 2.5. 
// You get 2.

Why? An int divided by an int results in an int. The decimal part is purely truncated (chopped off), not rounded. To fix this, cast one side to a double: double result = (double)a / b;.

Assignment Operators

= is assignment, not "equals" (math class lied to you).

  • x = 5: Put 5 into x.
  • x += 5: Add 5 to whatever is currently in x, and save the result (Same as x = x + 5).

Increment/Decrement

  • x++ (Post-increment): Use x, then add 1.
  • ++x (Pre-increment): Add 1, then use x.

Industry Tip: Prefer ++x (Pre-increment) in loops. Historically, it is slightly faster because it doesn't have to create a temporary copy of the variable before adding to it. In modern compilers, it often doesn't matter, but it's a good habit.

Comparison & Logic

Used in if statements (which we will learn later). These return true or false.

  • == : IS EQUAL TO (Don't confuse with =)
  • != : Not equal
  • && : AND (Both must be true)
  • || : OR (At least one must be true)

Short-Circuit Evaluation:
If you write A && B, and A is false, the computer won't even look at B. It already knows the result is false. This is a great performance feature.


4. I/O Streams: Talking to the User with cin and cout 🗣️

The Problem

Your code runs inside the CPU. You, the human, exist outside the computer case. We need a portal to send messages back and forth.

The Solution: <iostream>

The standard input/output library. It treats data like a Stream (a river of bytes) flowing in or out of the program.

  • std::cout (Character OUTput): Prints to console. Used with insertion operator <<.
  • std::cin (Character INput): Reads from keyboard. Used with extraction operator >>.

The "Hello World" Breakdown

cpp
#include <iostream> // 1. Include the library

int main() {
    int age;
    
    // Output: Sending data out to the screen
    std::cout << "Enter your age: "; 
    
    // Input: User types 25 and hits enter. 
    // The data flows from keyboard >> into variable.
    std::cin >> age;
    
    std::cout << "You are " << age << " years old." << std::endl;
    
    return 0;
}

⚠️ Common Pitfalls

  1. std::endl vs \n:

    • std::cout << "Hi" << std::endl; prints "Hi", moves to a new line, and flushes the buffer (forces the text to appear immediately). This can be slow if done 1000 times a second.
    • std::cout << "Hi\n"; just moves to a new line. It is faster. Use \n unless you specifically need to force the output to appear right now (like when debugging a crash).
  2. The Space Issue with cin:
    If you type "John Doe" into std::cin >> name;, name will only contain "John".
    Why? cin considers a space to be the end of the input.
    Fix: Use std::getline(std::cin, name); to read a whole line of text including spaces.

  3. Namespaces:
    You will see tutorials using using namespace std; at the top of files.
    Industry Standard: Avoid this in large projects. It creates "naming collisions" (e.g., if you create a function named cout, it confuses the compiler with std::cout). Typing std:: is good exercise for your fingers.


🧠 Real World Scenario: The Bank ATM

Let's put it all together in a simulation of an ATM backend.

cpp
#include <iostream>
#include <string>

int main() {
    // CONSTANT: The bank fee never changes during a transaction
    const double transactionFee{1.50};
    
    // VARIABLE: User's balance
    double balance{100.00};
    
    std::cout << "Current Balance: $" << balance << "\n";
    std::cout << "Withdrawal amount: ";
    
    double withdrawAmount{0.0};
    std::cin >> withdrawAmount;
    
    // OPERATOR logic
    // Check if they have enough money AND the fee
    bool isTransactionValid = (balance >= (withdrawAmount + transactionFee));
    
    // Boolean printed as 1 (true) or 0 (false) by default
    std::cout << "Transaction Approved: " << isTransactionValid << "\n";
    
    // LOGIC: Short circuit calculation (simple version)
    // In real code we use 'if', but here is a math trick:
    // If valid (1), we subtract. If invalid (0), we subtract 0.
    balance = balance - ( (withdrawAmount + transactionFee) * isTransactionValid );
    
    std::cout << "New Balance: $" << balance << std::endl;
    
    return 0;
}

📚 Further Reading & References

Next Step

Now that we have data and can do math, we need to control the flow of the program. Next up: Conditionals and Loops.

Challenge

Challenge: C++ Itemized Receipt Calculator

Write a C++ program that functions as a simple point-of-sale terminal. The program should calculate the total cost for a single item type, including sales tax, and then compute the change due to the customer.

Requirements:

  1. Include the necessary headers: <iostream>, <string>, and <iomanip>.
  2. Inside main, define a const double for the sales tax rate and initialize it to 0.0875.
  3. Prompt the user to enter the item's name (which may include spaces) and read the entire line of input into a std::string variable.
  4. Prompt the user to enter the item's price and the quantity being purchased. Store these in variables of appropriate types.
  5. Declare and initialize all non-constant variables using modern brace initialization (e.g., int quantity{0};).
  6. Calculate the subtotal before tax. Ensure your calculation avoids integer division pitfalls.
  7. Calculate the sales tax amount and the final total cost.
  8. Prompt the user for the amount of cash paid by the customer.
  9. Calculate the change to be returned.
  10. Display a formatted receipt that shows the item name, subtotal, tax amount, final total, cash paid, and the change due. All monetary values in the output must be formatted to show exactly two decimal places.
  11. You must use the std:: prefix for all standard library components (e.g., std::cout, std::string). Do not use using namespace std;.
  12. Use ' ' for all newlines in your output.

Expected result

The user's code must correctly implement a C++ program that performs the following actions:

  1. A const double for the sales tax rate is declared and initialized to 0.0875.
  2. The program correctly prompts for and reads an item name containing spaces using std::getline(std::cin, ...). An std::cin.ignore() may be necessary after reading previous numerical input to clear the buffer before std::getline.
  3. The program reads a double for the price and an int for the quantity.
  4. All variables that are not constants are initialized using brace syntax (e.g., double price{0.0};).
  5. It correctly calculates the subtotal (price * quantity), tax (subtotal * sales_tax_rate), final total (subtotal + tax), and change (cash_paid - total). The calculation must not suffer from integer division issues.
  6. The final output is a clearly formatted receipt. All floating-point values representing currency (subtotal, tax, total, etc.) must be displayed with exactly two decimal places, which requires the use of std::fixed and std::setprecision(2) from the <iomanip> library.
  7. The code must explicitly use the std:: namespace prefix for all standard library functions and types (std::cout, std::cin, std::string, etc.) and must not contain the using namespace std; directive.
cpp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.