2

I am working on a simple function that, given an input n, returns n Fibonacci's numbers.

int main(){
    int n = 0;
    int counter = 1;
    int f1, f2, f3 = 1;
    printf("Insert an integer bigger than 0:\n");
    scanf("%i", &n);
    printf("%i", f1);
    while(counter <= n){
            f3 = f1 + f2;
            printf("%i\n", f3);
            f1 = f2;
            f2 = f3;
            counter = counter + 1;
    }
    return 0; 
 }

Surprisingly, the function returns different results each time I run the program. Furthermore, these numbers are far bigger/smaller than any possible result.

Most likely, I am missing something obvious, but I cannot explain such a behavior.

Worice
  • 3,847
  • 3
  • 28
  • 49
  • 2
    `printf("%i", f1);` What do you think the value of `f1` should be at that stage? – kaylum Jan 19 '17 at 01:38
  • int f1,f2,f3=1 ====> is f1 and f2 intialized ? – dormi330 Jan 19 '17 at 01:38
  • Should not it be 1? – Worice Jan 19 '17 at 01:38
  • @Worice Perhaps it *should* be, but it isn't. Arguably C would be a slightly easier language if that is how it works, but you have to deal with the language as it actually exists. In any event, you could always simply declare them uninitialized in one line and write `f1 = f2 = f3 = 1;` in the next. – John Coleman Jan 19 '17 at 01:41
  • @JohnColeman you are right, I will keep it in mind. I did not think that the random numbers could be a consequence of unassigned variables. – Worice Jan 19 '17 at 01:43

1 Answers1

7

This line:

int f1, f2, f3 = 1;

only initialize f3 to 1, it does not initialize f1 and f2. You should use this instead:

int f1 = 1, f2 = 1, f3 = 1;

to initialize all three.

fluter
  • 13,238
  • 8
  • 62
  • 100
  • I had only a slightly suspect that the random number could be a consequence of unsigned variables, but I negated the idea. Quite naive. Thanks. – Worice Jan 19 '17 at 01:46
  • Or use different statements to declare different variables. This also avoids the `int * a, b;` [problem](http://stackoverflow.com/q/6990726/589924). – ikegami Jan 19 '17 at 02:18
  • Right, it's always clearer to declare each variable separately. `int f1 = 1; int f2 = 1; int f3 = 1;` – fluter Jan 19 '17 at 02:20