returning value of function by static pointer

Mar 4, 2014 at 12:37pm

Hi.I have to create function that returns the next value in fibonachi sequence every time i call it.The argument of the function must be of bool type and by default is false.When I give true to the function it must reset the function to the begining fo the Fibonachi sequence .The result is not what I expect and I cannot debug (I dont know why) code to find out what the problem is.
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
  #include<iostream>
using namespace std;
int pfs[]={1,1,2,3,5,8};
int fib(bool);

int main()
{
    cout<<fib(false)<<endl;
    for(int i=0;i<6;i++)
        cout<<fib(true)<<endl;
    getchar();   
}
int fib(bool f=false)
    {
    static int* pi;
    if(f=true)
	{
		pi=pfs;
		return *pi;
	}
    else
        { 
		pi++;
		return *pi;
        }   
    }
Mar 4, 2014 at 1:04pm
Line 16. Assignment does not belong there. If you had written true=f, the compiler would have noticed.


PS. I'm quite sure that default parameters belong to declaration, not to implementation.
Mar 4, 2014 at 4:18pm
Why did you use it?
int pfs[] = {...}; //this is none-static array of int, and...
static int* pi; //NONE-STATIC POINTER of static int
Then the fib() is calling, it makes pi = nullptr again-and-again;
And why are you assigning f with true and check it everytimes; //if(f = true) != if(f == true)
Last edited on Mar 4, 2014 at 4:24pm
Mar 4, 2014 at 4:47pm
exru has a point, since the first time you call fib you pass false, the "corrected" program would increment pi (which has an undefined value) and then try to dereference it (segfault if you are lucky).
Last edited on Mar 5, 2014 at 7:08pm
Mar 4, 2014 at 5:06pm
My fault.I missed "=" and swaped true and false in main() and now it's OK.Thanks
Mar 5, 2014 at 4:50pm
L B (8788) indeed! But i was seeing this mistake before. My specialization is php, but bugs is bugs independently of language. This is program needs refactoring before it will be start :)
Last edited on Mar 5, 2014 at 4:55pm
Topic archived. No new replies allowed.