c语言静态函数调用静态变量
Program 1:
程序1:
#include <iostream>
using namespace std;
int static fun(int x, int y)
{
return (x + y);
}
int main()
{
int K = 0;
K = fun(10, 20);
cout << K << endl;
return 0;
}
Output:
输出:
30
Explanation:
说明:
Here, we created a static function taking two arguments x and y and returning the sum of both. And in the main() function, we created a local variable K to store the result returned by function fun() and then print K using cout.
在这里,我们创建了一个带有两个参数x和y并返回两者之和的静态函数。 在main()函数中,我们创建了一个局部变量K来存储函数fun()返回的结果,然后使用cout打印K。
Program 2:
程式2:
#include <iostream>
using namespace std;
int* fun()
{
static int a;
a++;
return &a;
}
int main()
{
int* p;
p = fun();
p = fun();
p = fun();
p = fun();
cout << "function called " << *p << " times";
return 0;
}
Output:
输出:
function called 4 times
Explanation:
说明:
Here, we created a function that contains a static variable a and function returns an integer pointer.
在这里,我们创建了一个包含静态变量a的函数,并且该函数返回一个整数指针。
Now, look at the main() function, here we created an integer pointer p that is storing the address returned by function fun(), after every function call, static variable increased, because the default value of the static variable is 0 and then its lifetime is in the whole program.
现在,查看main()函数,在这里我们创建了一个整数指针p ,该指针存储着fun()函数返回的地址,在每次调用函数之后,静态变量都会增加,因为静态变量的默认值为0,然后它的寿命在整个程序中。
In the main() function we called function fun() 4 times, that's why it will print "function called 4 times" on the console screen.
在main()函数中,我们将函数fun()调用了4次,这就是为什么它将在控制台屏幕上打印“调用4次的函数”的原因。
Program 3:
程式3:
#include <iostream>
using namespace std;
int* fun()
{
static int a;
a++;
return &a;
}
int main()
{
int* p;
p = fun();
fun();
fun();
fun();
cout << "function called " << *p << " times";
return 0;
}
Output:
输出:
function called 4 times
Explanation:
说明:
Here, we created a function that contains a static variable a, and the function returns an integer pointer.
在这里,我们创建了一个包含静态变量a的函数,该函数返回一个整数指针。
Now, coming to the main() function, here we created an integer pointer p that is storing the address returned by function fun(), after every function call, the static variable increased because the default value of the static variable is 0 and then its lifetime is in the whole program.
现在,进入main()函数,在这里我们创建了一个整数指针p ,该指针存储着fun()函数返回的地址,在每次调用函数之后,静态变量都会增加,因为静态变量的默认值为0,然后它的寿命在整个程序中。
In the main() function, we called function fun() 4 times, but the pointer has the address of the static variable in the first function call. As we know that, the lifetime of the main() function is in the whole program, that's why static variable will not release allocated space for the static variable then the address of a will not change and we got the latest value of static variable a, using the pointer.
在main()函数中,我们调用了fun()函数4次,但是指针在第一个函数调用中具有静态变量的地址。 正如我们所知道的是,在main()函数的寿命是在整个程序中,这就是为什么静态变量不会释放分配的空间的静态变量,然后的地址不会改变,我们得到了静态变量的最新值,使用指针。
c语言静态函数调用静态变量