Chinaunix首页 | 论坛 | 博客
  • 博客访问: 209648
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: C/C++

2011-03-15 09:51:34

In C, all function arguments are passed "by value.". This means that the called function is given the values of its arguments in temporary variables rather than the originals.

Call by value is an asset, however, not a liability. It usually leads to more compact programs with fewer extraneous variables, because parameters can be treated as coveniently initialized local variables in the called routine.

For example,

  1. /* power: raise base to n-th power; n >= 0 */
  2. int power (int base, int n)
  3. {
  4.     int p;

  5.     for (p = 1; n > 0 ; --n)
  6.      p = p * base;
  7.     return p;
  8. }


The parameter n is used as a temporary variable, adn is counted down (a for loop that runs backwards) until it becomes zero; there is no longer a need for the variable i. Whatever is done to n inside power has no effect on the argument that power was originally called with.

The story is different for arrays. When the name of an array is used as an argument, the value passed to the function is the location or address of the beginning of the array --- there is no copying of array elements. By subscripting this vaule, the function can access and alter any argument of the array.
阅读(1233) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~