2011年11月8日 星期二

[C] call by value/reference/address

Call by Value, Call by Address(Pointer), C++ includes Call by Reference
http://csie-tw.blogspot.com/2010/03/call-by-valuecall-by-pointercall-by.html

Call by Value:
int main()
{
  int x=1;
  printf("x=%d\n", x);
  foo(x);
  printf("x=%d\n", x);
}
void foo(int x)
{
  x++;
}

result:
1
1


Call by Address/Pointer:
int main()
{
  int x=1;
  printf("x=%d\n", x);
  foo(&x);
  printf("x=%d\n", x);
}
void foo(int *x)
{
  (*x)++;
}

result:
1
2


Call by Reference:(C++)
int main()
{
  int x=1;
  printf("x=%d\n", x);
  foo(x);
  printf("x=%d\n", x);
}
void foo(int &x)
{
  x++;
}

result:
1
2

沒有留言:

張貼留言