كيفية التعامل مع المتغيرات الثابتة في لغة سي
داخل الوظيفة ، يمكنك تهيئة ملفمتغير ثابتباستخدامstatic
كلمة رئيسية.
لقد قلت "داخل دالة" ، لأن المتغيرات العامة تكون ثابتة بشكل افتراضي ، لذلك ليست هناك حاجة لإضافة الكلمة الأساسية.
ما هو المتغير الثابت؟ يتم تهيئة المتغير الثابت إلى 0 إذا لم يتم تحديد قيمة أولية ، ويحتفظ بالقيمة عبر استدعاءات الوظائف.
ضع في اعتبارك هذه الوظيفة:
int incrementAge() {
int age = 0;
age++;
return age;
}
إذا اتصلناincrementAge()
مرة واحدة ، سوف نحصل عليها1
كقيمة العودة. إذا أطلقنا عليها أكثر من مرة ، فسنحصل دائمًا على 1 مرة أخرى ، لأنage
هو متغير محلي وتمت إعادة تهيئته إلى0
في كل مكالمة وظيفة واحدة.
إذا قمنا بتغيير الوظيفة إلى:
int incrementAge() {
static int age = 0;
age++;
return age;
}
الآن في كل مرة نسمي هذه الوظيفة ، نحصل على قيمة متزايدة:
printf("%d\n", incrementAge());
printf("%d\n", incrementAge());
printf("%d\n", incrementAge());
سوف يعطينا
1
2
3We can also omit initializing age
to 0 in static int age = 0;
, and just write static int age;
because static variables are automatically set to 0 when created.
We can also have static arrays. In this case, each single item in the array is initialized to 0:
int incrementAge() {
static int ages[3];
ages[0]++;
return ages[0];
}
Download my free C Handbook
More clang tutorials:
- Introduction to the C Programming Language
- C Variables and types
- C Constants
- C Operators
- C Conditionals
- How to work with loops in C
- Introduction to C Arrays
- How to determine the length of an array in C
- Introduction to C Strings
- How to find the length of a string in C
- Introduction to C Pointers
- Looping through an array with C
- Booleans in C
- Introduction to C Functions
- How to use NULL in C
- Basic I/O concepts in C
- Double quotes vs single quotes in C
- How to return a string from a C function
- How to solve the implicitly declaring library function warning in C
- How to check a character value in C
- How to print the percentage character using `printf()` in C
- C conversion specifiers and modifiers
- How to access the command line parameters in C
- Scope of variables in C
- Can you nest functions in C?
- Static variables in C
- C Global Variables
- The typedef keyword in C
- C Enumerated Types
- C Structures
- C Header Files
- The C Preprocessor