1. مفهوم النطاق (Scope) مقابل دورة الحياة (Lifetime)
1. Scope (Visibility) vs Lifetime (Duration)
Variable Scope, Shadowing, Lifetime & Storage Classes in C
شرح شامل ومفصل لنطاقات المتغيرات (Scope) ودورة حياتها (Lifetime): المتغيرات المحلية (Local) مقابل العامة (Global)، ظاهرة حجب المتغيرات (Variable Shadowing)، فئات التخزين الأربعة (auto, static, extern, register)، والممارسات الهندسية الفضلى لتجنب الأخطاء القاتلة كالـ Dangling Pointers.
مكسل تقرأ؟ شغّل القارئ المصري (د. شاكر أو د. سلمى) وهيمشي معاك كلمة بكلمة ويظللها بالأحمر في مكانها داخل المحاضرة ويسكرول أوتوماتيك!
1. Scope (Visibility) vs Lifetime (Duration)
2. The Three Levels of Scope in C
| 1 | #include <stdio.h> |
| 2 | |
| 3 | // Global variable (File Scope) |
| 4 | int globalCount = 100; |
| 5 | |
| 6 | void testScope(void) { |
| 7 | // Local variable (Block Scope) |
| 8 | int localVal = 10; |
| 9 | |
| 10 | if (localVal > 5) { |
| 11 | // Inner block variable |
| 12 | int innerVal = localVal * 2; |
| 13 | printf("Inner: %d, Global: %d\n", innerVal, globalCount); |
| 14 | } |
| 15 | // innerVal is dead here! |
| 16 | } |
| 17 | |
| 18 | int main(void) { |
| 19 | testScope(); |
| 20 | return 0; |
| 21 | } |
3. Variable Shadowing & Identifier Masking
| 1 | #include <stdio.h> |
| 2 | |
| 3 | int x = 50; // Global x |
| 4 | |
| 5 | int main(void) { |
| 6 | int x = 10; // Shadows global x! |
| 7 | printf("Outer main x: %d\n", x); // Prints 10 |
| 8 | |
| 9 | { |
| 10 | int x = 99; // Shadows main's local x! |
| 11 | printf("Inner block x: %d\n", x); // Prints 99 |
| 12 | } |
| 13 | |
| 14 | printf("Back in main x: %d\n", x); // Prints 10 |
| 15 | return 0; |
| 16 | } |
4. C Storage Classes: auto, static, extern, register
| 1 | #include <stdio.h> |
| 2 | |
| 3 | void counterFunction(void) { |
| 4 | auto int normalCounter = 0; // Re-initialized to 0 on EVERY call |
| 5 | static int staticCounter = 0; // Initialized ONCE at program startup |
| 6 | |
| 7 | normalCounter++; |
| 8 | staticCounter++; |
| 9 | |
| 10 | printf("auto: %d | static: %d\n", normalCounter, staticCounter); |
| 11 | } |
| 12 | |
| 13 | int main(void) { |
| 14 | counterFunction(); // auto: 1 | static: 1 |
| 15 | counterFunction(); // auto: 1 | static: 2 |
| 16 | counterFunction(); // auto: 1 | static: 3 |
| 17 | return 0; |
| 18 | } |
5. Critical Pitfalls: Dangling Pointers & Escaping Stack Memory
c
int* badFunction() {
int secret = 42;
return &secret; // خطأ كارثي! المتغير secret يموت بمجرد تنفيذ return
}
``
عندما تنتهي الدالة، يتم هدم الـ Stack Frame الخاص بها. المؤشر المرتجع يصبح Dangling Pointer يُشير إلى موقع ذاكرة غير صالح، وقراءته تسبب سلوكاً غير محدد (Undefined Behavior) أو Segmentation Fault.تسجيلات المحاضرات وبودكاست المراجعة الذكية للفرقة الثالثة
بودكاست حواري ذكي يلخص كافة المفاهيم الصعبة ومسائل الشيت بطريقة سهلة المراجعة أثناء التنقل.