mirror of
https://github.com/kamranahmedse/developer-roadmap.git
synced 2026-09-24 15:00:31 +08:00
fix: code blocks in "Scope in C++" (#9734)
This commit is contained in:
@@ -4,6 +4,7 @@
|
||||
|
||||
* **Global scope:** Identifiers declared outside any function or class have a global scope. They can be accessed from any part of the program (unless hidden by a local identifier with the same name). The lifetime of a global identifier is the entire duration of the program.
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
int globalVar; // This is a global variable
|
||||
@@ -11,10 +12,11 @@
|
||||
int main() {
|
||||
std::cout << "Global variable: " << globalVar << '\n';
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
* **Local scope:** Identifiers declared within a function or a block have a local scope. They can be accessed only within the function or the block they were declared in. Their lifetime is limited to the duration of the function/block execution.
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
void localExample() {
|
||||
@@ -27,10 +29,11 @@
|
||||
localExample();
|
||||
// std::cout << localVar << '\n'; //error: ‘localVar’ was not declared in this scope
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
* **Namespace scope:** A namespace is a named scope that groups related identifiers together. Identifiers declared within a namespace have the namespace scope. They can be accessed using the namespace name and the scope resolution operator `::`.
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
namespace MyNamespace {
|
||||
@@ -40,10 +43,11 @@
|
||||
int main() {
|
||||
std::cout << "Namespace variable: " << MyNamespace::namespaceVar << '\n';
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
* **Class scope:** Identifiers declared within a class have a class scope. They can be accessed using the class name and the scope resolution operator `::` or, for non-static members, an object of the class and the dot `.` or arrow `->` operator.
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
|
||||
class MyClass {
|
||||
@@ -61,6 +65,6 @@
|
||||
std::cout << "Static member: " << MyClass::staticMember << '\n';
|
||||
std::cout << "Non-static member: " << obj.nonStaticMember << '\n';
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Understanding various types of scope in C++ is essential for effective code structuring and management of resources in a codebase.
|
||||
Reference in New Issue
Block a user