I was messing around just trying to understand how c++ works, when I got "crashed" by the int arrayF[0];
on line 6, and int arrayF[input];
on line 21. In the computer memory the first version of this arrayF shouldn't be overwrote by the one on line 21? I know that int arrayF[input];
is in another scope, but still do what is supposed to do, or not?
And I tested another thing(don't know why) removing the int from int arrayF[input];
on line 21 like I was trying to access that address and somehow, the program works as intended. Why? This should arise a error by trying to access a unexistent address.
Yes, this a fibonacci program, my intention is not make this exactualy right, I'm just messing with the language.
#include <iostream>
#include <string>
using namespace std;
int arrayF[0];
int fiboR(int i, int n)
{
if(i == n) return arrayF[n];
else
arrayF[i + 2] = arrayF[i] + arrayF[i + 1];
return fiboR(i + 1, n);
}
int main(int argc, char *argv[])
{
int input = stoul(argv[argc - 1]);
int start = stoul(argv[argc - 2]);
int arrayF[input];
arrayF[0] = 0;
arrayF[1] = 1;
cout << fiboR(start, input) << "\n";
return 0;
}
The program works by calling it with command-line arguments, the 0 is the first fibonacci's sequence index, a start argument. The next numer is the desired index of the fibonacci's sequence
Output with int arrayF[input];
on line 21:
$ ./a.out 0 10
0
Output with arrayF[input];
on line 21:
$ ./a.out 0 10
55