Hi,
I cannot understand why the following happens, please read to the end.
The code below outputs this:
a[]= 00
a[]= 10
a[]= 10
a[]= 10
a[]= 11
a[]= 11
0.
But I was expecting this:
a[]= 00
a[]= 10
a[]= 10
a[]= 00
a[]= 01
0.
This describes how the process is running in machine:
1. Defining a[2]{0,0}; ii=0; aj=0
2. Calling function func(a,ii,aj) |func({0,0},0,0)|
3. func({0,0},0,0) defining w=0; static aa=0
4. func({0,0},0,0) if(0) returns aa=1
5. func({0,0},0,0) for j=0
6. func({0,0},0,0) for Outputing "00", because a[2]={0,0}, look (1).
7. func({0,0},0,0) for if(!0) | because a[0]=0| returns w+=func(a,ii+1,j) |func({0,0},0+1,0)| and calls func({0,0},1,0)
8. func({0,0},0,0) for if func({0,0},1,0) defining w=0
9. func({0,0},0,0) for if func({1,0},1,0) if(1) returns a[0]=1, because of static aa=1, см 4.
10. func({0,0},0,0) for if func({1,0},1,0) for j=0
11. func({0,0},0,0) for if func({1,0},1,0) for Outputing "10", because of a[2]={1,0}, look row #9
12. func({0,0},0,0) for if func({1,0},1,0) for if(!1) |because a[0]=1|
13. func({0,0},0,0) for if func({1,0},1,0) for j=1
14. func({0,0},0,0) for if func({1,0},1,0) for Outputing "10"
15. func({0,0},0,0) for if func({1,0},1,0) for if(!0) |because a[1]=0|
16. func({0,0},0,0) for if func({1,0},1,0) for if if(1==1) |because ii=1, func({0,0},ii,0)|
17. func({0,0},0,0) for if func({1,0},1,0) for if if return 0
18. func({0,0},0,0) for if w=0 |because func({1,0},1,0) gives 0|
19. func({0,0},0,0) for j=1
And from now, something is happening that I cannot understand:
20. func({0,0},0,0) for Outputing "10"
Why so? If func has itselfs local variables, including a[2]={0,0}.
I was expecting this:
20. func({0,0},0,0) for Outputing "00"
So a[2] array is not local variable. Why it happens?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
#include <iostream>
using namespace std;
int func(bool a[],int ii,int aj)
{
int w=0;
static bool aa=0;
if(aa){a[aj]=1;}else{aa=1;}
for(int j=0;j<2;j++)
{
cout<<"a[]= "<<a[0]<<a[1]<<endl;
if(!a[j])
{
if(ii==1){return 0;}
else{w+=func(a,ii+1,j);}
}
}
return w;
}
int func()
{
bool a[2];
for(int i=0;i<2;i++)a[i]=0;
int ii=0,aj=0;
return func(a,ii,aj);
}
void main()
{
cout<<func();
getchar();getchar();
}
|
But if I define array a[2] as a vector, all goes fine.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <vector>
using namespace std;
int func(vector<bool> a,int ii,int aj)
{
int w=0;
static bool aa=0;
if(aa){a[aj]=1;}else{aa=1;}
for(int j=0;j<2;j++)
{
cout<<"a[]= "<<a[0]<<a[1]<<endl;
if(!a[j])
{
if(ii==1){return 0;}
else{w+=func(a,ii+1,j);}
}
}
return w;
}
int func()
{
vector<bool> a(2);
for(int i=0;i<2;i++)a[i]=0;
int ii=0,aj=0;
return func(a,ii,aj);
}
void main()
{
cout<<func();
getchar();getchar();
}
|