current position:Home>C + + question, what is the running process of the following program?

C + + question, what is the running process of the following program?

2022-01-27 02:56:46 CSDN Q & A

#include<iostream.h>
int f(int);
int main()
return 0;
{
for(i=0;i<5;i++)
int i;
cout<<f(i)<<" ";
return 0;
}
int f(int i)
{
static int k=1;
for( ;i>0;i--) k+=i;
return k;
}
answer 1 2 5 11 21




Refer to the answer 1:

Notice the K Is static , So after each output K The value of is not restored
i:0 k=1+0=1
i:1 k=1+(1+0)=2
i:2 k=2+(2+1+0)=5
i:3 k=5+(3+2+1+0)=11
...




Refer to the answer 2:



Refer to the answer 3:
#include<iostream>using namespace std;int f(int);int main(){    int i;    for (i = 0; i < 5; i++)    cout << f(i) << " ";    return 0;}int f(int i){    static int k = 1;    for (; i > 0; i--) k += i;    return k;}



Refer to the answer 4:

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270256444472.html

Random recommended