11.2 C++ Basics & Debugging Concepts
Key Takeaways
- C++ is statically typed: you declare types (`int`, `double`, `char`, `bool`, etc.) and the compiler checks them before the program runs
- `cout` sends output to the console; `cin` reads input — know the direction even if you never write a full I/O program on paper
- A pointer holds a memory address; `*` dereferences (access the value at the address) and `&` takes an address — exam depth is conceptual, not advanced pointer arithmetic
- Compile-time errors stop the build (syntax/type issues); runtime errors appear while the program executes (divide by zero, bad memory use, logic that crashes)
- Print-debugging means inserting temporary output of key variables to locate where actual state diverges from expected state
Where Python emphasizes readable scripting, C++ emphasizes typed, compiled programs closer to systems and performance-sensitive code. The Cyber Test will not expect you to write production C++ or master templates and the STL. It does expect recognition of basic type declarations, how console input/output is directed, what a pointer is at a conceptual level, and how to classify and hunt bugs.
This section is deliberately exam-light: enough C++ surface to read a short snippet, plus a debugging playbook that transfers to any language you meet in training or on the job.
Compiled vs Interpreted (Why C++ Feels Different)
Python typically runs through an interpreter (or compiles to bytecode behind the scenes) and tells you about many mistakes only when that line executes. Classic C++ workflow:
- You write source (
.cpp). - A compiler translates it to machine code (object files → executable).
- You run the executable.
If the compiler rejects the program, you never get a run. That split creates two big error buckets — compile-time and runtime — that aptitude questions love to contrast.
Types You Should Recognize
C++ is statically typed: variables have declared types that the compiler checks.
| Type | Role | Example declaration |
|---|---|---|
int | Integer | int count = 0; |
double / float | Floating-point | double ratio = 0.5; |
char | Single character | char grade = 'B'; |
bool | Boolean | bool ok = true; |
string | Text (with <string>) | string name = "host1"; |
Declarations look like type name = value;. Semicolons end statements. Unlike Python, types are explicit in beginner snippets (modern C++ has auto, but exam items usually show clear types).
Type mismatch intuition
If code tries to treat a string as an integer without a conversion, the compiler often flags it. That is a feature: many bugs die before the program runs. On a multiple-choice item, “this will not compile” is a real option when types or syntax are inconsistent.
Simple operators
Arithmetic (+ - * / %), comparison (== != < > <= >=), and assignment (=) appear as in other languages. Watch integer division: in C++, 5 / 2 is 2 when both operands are int, because the fractional part is truncated toward zero for positive values. That is a frequent trap when candidates expect 2.5.
cout and cin Conceptually
Console I/O in teaching C++ uses streams from <iostream>:
#include <iostream>
using namespace std;
int main() {
int port;
cout << "Enter port: ";
cin >> port;
cout << "You entered " << port << endl;
return 0;
}
Direction mnemonic:
cout << value— arrows point toward the output stream (console output).cin >> variable— arrows point into the variable (console input).
You may see endl (end line / flush) or "\n" for newlines. Exam questions often ask what gets printed or which variable receives input — not how to optimize stream performance.
If a snippet never calls cin, do not invent user input; use the literals shown in the code.
Pointers at Exam-Light Depth
A pointer is a variable that stores a memory address of another value.
int x = 10;
int* p = &x; // p holds the address of x
cout << *p; // dereference: print 10 (the value at that address)
*p = 20; // change x through the pointer; x is now 20
Core symbols:
| Symbol | Meaning |
|---|---|
&x | Address of x |
int* p | p is a pointer to int |
*p | Value at the address stored in p (dereference) |
What you need for the Cyber Test
- Pointers refer to locations, not (primarily) to “the number itself.”
- Dereferencing access or updates the pointed-to object.
- A pointer that does not point at valid memory is dangerous; dereferencing it can cause a runtime crash (undefined behavior in real C++).
You do not need deep pointer arithmetic, multiple indirection forests, or custom allocators for this exam. If an item shows *p and &x, translate to “value at” and “address of.”
Analogy for cyber context
Think of a pointer like a ticket that says which locker holds the data. The ticket is not the laptop inside the locker; opening the locker (*) gets you the laptop. Copying the ticket (q = p) means two tickets to the same locker — changing contents through either ticket changes the same object.
Compile-Time vs Runtime Errors
Compile-time errors
Detected when building the program. Common causes:
- Missing semicolons or mismatched braces/parentheses
- Undeclared identifiers (typo in a variable name)
- Type mismatches the language rejects
- Missing
#includefor a facility the code uses (conceptual awareness)
Symptom: No executable run — the compiler prints an error message and stops (or refuses to link).
Runtime errors
The program compiled and started, then failed during execution. Examples:
- Division by zero in some environments
- Dereferencing an invalid pointer
- Accessing an array out of bounds (may crash or corrupt silently — still a runtime defect)
- Infinite loops that hang the process (behavioral failure even without a crash message)
Symptom: Build succeeded; failure appears when that path executes.
Logic errors (still “bugs”)
The program runs and exits “successfully” but computes the wrong answer — for example, using < instead of <= in a loop bound. These are often the hardest to spot because there is no compiler error and no crash. Debugging is about comparing expected vs actual results.
| Category | When caught | Typical fix focus |
|---|---|---|
| Compile-time | Before run | Syntax, types, declarations |
| Runtime crash/fault | During run | Invalid memory, bad input assumptions |
| Logic error | By testing | Wrong condition, off-by-one, bad formula |
Exam tip: if the question says the compiler rejects the code, look for syntax/type issues. If it says the program crashes when run, look for runtime faults. If it prints a wrong number, hunt a logic error.
Print-Debugging: The Universal First Tool
Print-debugging (also called printf-debugging even in C++) means temporarily inserting output statements to reveal program state:
cout << "i=" << i << " sum=" << sum << endl;
Or in Python from the previous section: print("i=", i, "sum=", sum).
A disciplined approach
- State the expected behavior — “After three iterations,
sumshould be 6.” - Pick observation points — before the loop, each iteration, after the loop.
- Compare — the first place actual values diverge from expected is near the bug.
- Remove or disable temporary prints once fixed so production output stays clean.
Print-debugging does not replace careful reading on a paper exam, but the same mental move applies: simulate what would be printed at each step. When a multiple-choice option matches an intermediate value, check whether the question asks for intermediate or final state.
Complementary checks
- Trace table on scratch paper (variable columns, one row per step).
- Binary search the bug — print halfway through a long function; decide which half is wrong; repeat.
- Reproduce with the smallest input that fails — fewer moving parts.
On the Cyber Test you rarely have a live debugger. Your brain plus a trace table is the debugger.
Mini C++ Trace (Types + Output)
int a = 5;
int b = 2;
int q = a / b;
int* p = &q;
*p = *p + 1;
cout << q;
Walkthrough:
- Integer division:
5 / 2→q = 2. ppoints atq.*p = *p + 1incrementsqto3.- Printed output:
3.
If someone mistakenly thinks / always yields a float, they might expect 2.5 and miss that q is int from the start.
Connecting Python and C++ for Exam Day
| Idea | Python flavor | C++ flavor |
|---|---|---|
| Block structure | Indentation | Braces { } |
| Types | Dynamic (usually) | Declared, checked at compile time |
| Output | print(...) | cout << ... |
| Address concept | Rare at intro level | Pointers & / * |
| Many errors | Runtime exceptions | Split across compile vs run |
You are not choosing a career language on the test. You are proving you can read a short program, respect its rules, and reason about errors. That skill transfers to Bash one-liners, PowerShell, and whatever stack your cyber pipeline uses later.
When you finish this chapter, you should be able to (1) predict list/dict/string/slice results in Python, (2) recognize C++ types and I/O direction, (3) explain pointers at locker-ticket depth, and (4) classify bugs as compile-time, runtime, or logic — then attack them with a deliberate print/trace strategy.
In introductory C++, what does the statement cin >> port; do?
A C++ program fails with a message about a missing semicolon and never starts running. Which category best fits this problem?
Given int x = 7; int* p = &x; what does *p represent?
What is the main purpose of print-debugging?