7. 模块化的使用函数2 Modularity Using Functions II

7.1 变量的作用域(scope)

局部变量:local
全局变量:global

变量和函数的scope都可以是全局、局部。

7.2 变量存储类

局部变量存储类
auto int/float/char num;
//自动存储类,如没有类的描述,默认为auto

static int/float miles;
//静态存储类,使程序保持这个变量和它最后的数值。
通常被用作跟踪这个函数中发生的事件的计数器。
在没有给出明确的初始化时,都被设置为0。

#include 
void teststat(); /* function prototype */

int main()
{
  int count; /* count is a local auto variable */

  for(count = 1; count <= 3; count++)
    teststat();

  return 0;
}

void teststat()
{
  static int num = 0; /* num is a local static variable */

  printf("The value of the static variable num is now %d\n", num);
  num++;
}

extern int/float price;//外部存储类
register int dist;//寄存器存储类

全局变量存储类
static
//在没有明确初始化时,静态全局变量和静态局部变量一样,被初始化为0

extern
//将一个源代码文件中声明的全局变量的scope扩展到另外的源代码文件中

7.3 引用传递

传递地址给函数

#include 
int main()
{
  int num;

  num = 22;
  printf("num = %d\n", num);
  printf("The address of num is %u\n", &num);//地址运算符&

  return 0;
}

pointer variable:能存储地址的变量叫指针变量

#include 
int main()
{
  int *milesAddr; /* declare a pointer to an int *///声明一个指向整型的指针
  int miles;      /* declare an integer variable */

  miles = 22; /* store the number 22 into miles */

  milesAddr = &miles; /* store the 'address of miles' in milesAddr */
  printf("The address stored in milesAddr is %u\n",milesAddr);
  printf("The value pointed to by milesAddr is %d\n\n", *milesAddr);

  *milesAddr = 158; /* set the value pointed to by milesAddr to 158 */
  printf("The value in miles is now %d\n", miles);

  return 0;
}
#include 
int main()
{
  void newval(float *);  /* prototype with a pointer parameter *///带有一个指针参数的函数原型
  float testval;

  printf("\nEnter a number: ");
  scanf("%f", &testval);

  printf("The address that will be passed is %u\n\n", &testval);

  newval(&testval);   /* call the function */

  return 0;
}

void newval(float *xnum)   /* function header using a pointer parameter */
{
  printf ("The address received is %u\n", xnum);
  printf("The value pointed to by xnum is: %5.2f \n", *xnum );
}

7.4 交换两个数的数值

#include 

void swap(float *, float *); /* function prototype */

int main()
{
  float firstnum, secnum;

  printf("Enter two numbers: ");
  scanf("%f %f", &firstnum, &secnum);

  printf("\nBefore the call to swap():\n");
  printf("  The value in firtsnum is %5.2f\n", firstnum);
  printf("  The value in secnum is %5.2f\n", secnum);

  swap(&firstnum, &secnum); /* call swap() */

  printf("\nAfter the call to swap():\n");
  printf("  The value in firstnum is %5.2f\n", firstnum);
  printf("  The value in secnum is %5.2f\n", secnum);
  
  return 0;
}

void swap(float *num1Addr, float *num2Addr)
{
  float temp;

  temp = *num1Addr; /* save firstnum's value */
  *num1Addr = *num2Addr; /* move secnum's value into firstnum */
  *num2Addr = temp; /* change secnum's value */
}

你可能感兴趣的:(7. 模块化的使用函数2 Modularity Using Functions II)