Module 4: Tokens and FundamentalsBeginner45 min read
Tokens, Variables, Scope & Storage Duration
Master C++ tokens (keywords, identifiers, literals), variable initialization, local/global/static scope, and storage duration.
Key Takeaways & Core Concepts
- Copy Init:
int x = 10; - Direct Init:
int x(10); - Brace / Uniform Init (C++11):
int x{10};— Preferred, because it prevents narrowing data loss (int x{3.14};fails to compile!). - Mistake: Reading an uninitialized local variable (
int x; cout << x;) -> Undefined Behavior! Always initialize variables at declaration.
1. Tokens in C++
Tokens are the smallest lexical building blocks recognized by the compiler:
- 1Keywords: Reserved words (
int,const,constexpr,class,return,auto,nullptr). - 2Identifiers: User-defined names (letters, digits,
_; cannot start with a digit; case-sensitive). - 3Literals: Fixed values (
42,3.14f,'A',"CodeZov",true,0xFF,1'000'000C++14 digit separators). - 4Operators & Punctuators:
+,=,<<,;,{}.
1. Local, Global & Static Storage Duration
1#include <iostream>
2int globalVal{100};
3
4void track() {
5 static int calls{0};
6 int local{1};
7 ++calls;
8 std::cout << "calls=" << calls << ", local=" << local << "\n";
9}
10
11int main() {
12 track();
13 track();
14 std::cout << "globalVal=" << globalVal << "\n";
15 return 0;
16}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
16 lines
Note: `static int calls` persists across function invocations; `local` resets each call.
2. Variable Initialization & Narrowing Safety
- Copy Init:
int x = 10; - Direct Init:
int x(10); - Brace / Uniform Init (C++11):
int x{10};— Preferred, because it prevents narrowing data loss (int x{3.14};fails to compile!).
3. Scope & Storage Duration
| Variable Kind | Memory Location | Lifetime | Default Value |
|---|---|---|---|
| Local (Automatic) | Stack | Enclosing {} block | Uninitialized (garbage!) |
| Global | Static Data Segment | Entire program | Zero-initialized |
| Static Local | Static Data Segment | Entire program | Zero-initialized once |
4. Common Mistakes & Best Practices
- Mistake: Reading an uninitialized local variable (
int x; cout << x;) -> Undefined Behavior! Always initialize variables at declaration.
Practice & AssessmentC++ Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)