Home > other >  Different results when initializing a variable inside and outside for loop
Different results when initializing a variable inside and outside for loop

Time:10-30

I have tried a backtracking algorithm and receive different results when I initialize a variable inside and outside a for loop, but I don't understand why.

#include <stdio.h>

int a[10];
int n;
int i;
int j;   //difference

void display(){
    for (i = 1; i <= n; i  ) printf("%d", a[i]);
    printf("%\n");
}

void Try(int k){
    for (j = 0; j <= 1; j  ){                //difference
        a[k] = j;
        if (k == n) display();
        else Try(k   1);
    } 
}

int main(){
    n = 2;
    Try(1);
}

and

#include <stdio.h>

int a[10];
int n;
int i;
//int j;   //difference

void display(){
    for (i = 1; i <= n; i  ) printf("%d", a[i]);
    printf("%\n");
}

void Try(int k){
    for (int j = 0; j <= 1; j  ){                //difference
        a[k] = j;
        if (k == n) display();
        else Try(k   1);
    } 
}

int main(){
    n = 2;
    Try(1);
}

The result of the first code is just 00, 01 but the result of the second code is 00, 01, 10, 11 (the expected result).

Why does it have that difference?

CodePudding user response:

In the first case: j is a global variable so when execute else Try(k 1); j is reinitialized with zero and after and exit Try(k 1); the value of j now equal 2, so it will exist the for loop and end your code.

But in the second case: j is a local variable so when entering try function again, it sees j as a different variable than the old j. It's not the same variable you try to access.

Be careful when you write a recursive function. Avoid global variables.

  • Related