Program not showing correct behavior

int static a = 10;
void add(int x , int y)
{
x++;
y++;
cout << "The value of static variable is " <<x<<endl;
cout << "The value of non-static variable is " <<y<<endl;
}
void add1(int x , int y)
{
x++;
y++;
cout << "The value of static variable is " <<x<<endl;
cout << "The value of non-static variable is "<<y<<endl;
}
int main()
{
int b = 1;
add(a,b);
add1(a,b);
system("pause");
}

global static is not showing the correct behavior i.e for the first time
the static variable must show the value 11 and then in the second function it must show 12 but it is just showing 11 both time i call the function?? I m not understanding y this is happening ???
Why should it change? You're passing a and b by value, so changes to the function parameters won't affect the original values. Pass by reference if you don't want to operate on copies.
Last edited on
You are passing the parameters by value. This means that x and y in your add functions are copies of the variable, and are not the actual variable themselves. Therefore when you change x, you're changing x, you're not changing a.

If you want these functions to actually change the passed variables, you'd need to pass the variables by reference:

1
2
3
4
5
6
7
void add(int& x , int& y) // <- note the & symbols
{
  x++;
  y++;
  cout << "The value of static variable is " <<x<<endl;
  cout << "The value of non-static variable is " <<y<<endl;
}



Of course, if you'll try this, you'll see that static vs. non-static makes no difference here.


EDIT: bah you guys are too fast!
Last edited on
Topic archived. No new replies allowed.