Variables can shadow each other. You don't have to ensure that you never, ever use i
anywhere else in fear of messing with the i
in your for loop, because a new scope will get a new copy of the same name (like when two different people have the same name).
To fix this, you can return the value from your calculate function. I named it x2
to clearly differentiate it from your original x
:
int calculate(int x2){
x2 = x2 + 2;
return x2;
}
int main(){
int x = 0;
int i;
for(i=0;i<10;i++){
x = calculate(x);
}
printf("i = %d, x = %d\n", i, x);
}