English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C / C ++How to return an array from a function in C?

Static variables are variables that remain in memory during program execution, i.e., their lifetime is the entire duration of the program run. This is different from automatic variables, which are retained in memory only during the execution of the function and are destroyed at the end of the function.

Static variables are stored in the data segment of memory. The data segment is part of the program's virtual address space.

All static variables that are not explicitly initialized or initialized to zero are stored in the uninitialized data segment (also known as the BSS segment). In contrast, initialized static variables are stored in the initialized data segment.

Here is an example:

static int x = 5;
static int y;
The static variable x is stored in the initialized data segment and the static variable y is stored in the BSS segment.

The following program demonstrates the use of static variables in C language:-

Example

#include<stdio.h>
int func() {
   static int i = 4 ;
   i++;
   return i;
}
int main() {
   printf("%d\n", func());
   printf("%d\n", func());
   printf("%d\n", func());
   printf("%d\n", func());
   printf("%d\n", func());
   printf("%d\n", func());
   return 0;
}

The output of the above program is as follows-

5
6
7
8
9
10

Now let's understand the above program.

in this functionfunc(), i is initialized to4The static variable. Therefore, it is stored in the initialized data segment. Then, i is incremented and its value is returned. The following code snippet shows this:-

int func() {
   static int i = 4 ;
   i++;
   return i;
}

within the functionmain(), which is a functionfunc()is called6times, and returns the value of i to be printed. Since i is a static variable, it will remain in memory during program execution and provide a consistent value. The following code snippet shows this:-

printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
printf("%d\n", func());
SQL Tutorial