“我们是伞兵,本来就该被包围的!”----《兄弟连》。
在战争中,伞兵天生就该被包围,而在编程语言中,函数生来就该被调用。在被调用的过程中,执行函数的指令,完成值和参数的传递。按照不同的传递方式,函数可以分为下面几类:
1、先来看返回变量、常量的函数:
1 #include
2 #include
3
4 int func(inta)5 {6 a=2*a*a;7 printf("a=%d\n",a);8 returna;9 }10 intmain()11 {12 int b=func(10);13 printf("b=%d\n",b);14 return 0;15 }
上面的函数是返回变量的值,如果把被调函数func中的变量a换成常量,程序依然能够得到正确结果。例如:
1 #include
2
3 intfunc()4 {5 const char a='W';6 printf("A=%c \n",a);7 returna;8 }9 intmain()10 {11 char b=func();12 printf("b=%c \n",b);13 return 0;14 }
1 #include
2 #include
3 #include
4
17 }18
19 intmain()20 {21 test02();22 return 0;23 }
运行程序,我们会发现,字符串数组没有被正确输出。下面再看一例:
1 #include
2 #include
3 #include
4
5 int*func()6 {7 int a = 10;8 return &a;9 }10 voidtest01()11 {12 int* p = func(); //这种调用,结果已经不重要了,因为a的内存(因该是a所指向的内存)13 //被系统释放了,我们没有权限区操作这块内存
14 printf("test01第一次:a=%d \n", *p); //第一次输出‘10’,因为系统默认为作者保留这段内存
15 printf("test02第二次:a=%d \n", *p); //第二次输出内容就不定了,系统已经将这段内存释放了
16 }17
18 intmain()19 {20 test01();21 return 0;22 }
1 #include
2 #include
3 #include
4
5 char*getString01()6 {7 char *str= malloc(); //在堆上定义字符串
17 }18
19 char*getString02()20 {21 char* str = "hello,world!"; //声明并定义字符串指针变量,字符串存储在数据区
23 }24 voidtest03()25 {26 char* p =NULL;27 p=getString02();28 printf("程序数据区字符串内容 :%s \n", p);29 }30 intmain()31 {32 test02();33 test03();34 return 0;35 }