Simple calculation in a function

advertisements

I'm trying to do the calculation inside a function, but i'm not sure why it's not working:

int calculate(int x){
  x = x + 2;
  return x;
}

int main(){
  int x = 0;
  int i;

  for(i=0;i<10;i++){
    calculate(x);
  }

  printf("i = %d, x = %d\n", i, x);
}

I understand that x is 0 every time it passes through the function. But how do I fix it? Supposedly i should return 10, and x should return 20.


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);
}