cpp / beginner
Snippet
Understanding Scope and Block Structure
Scope determines where variables can be accessed in your program. A variable defined inside a block (between curly braces) is only visible within that block. This concept is called block scope and helps organize code while preventing accidental variable misuse. Trying to access a variable outside its scope will cause a compilation error.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>int main() {int x = 10;if (x > 5) {int y = 20;std::cout << "Inside block: " << x + y << std::endl;}std::cout << "Outside block: " << x << std::endl;return 0;}
Breakdown
1
int x = 10;
Variable x is accessible everywhere inside main()
2
int y = 20;
Variable y only exists inside the if block
3
std::cout << x + y;
Works here because y is in scope inside the block