且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

linux下C语言之调用简单函数

更新时间:2022-09-13 19:22:31

今天我们来学习下简单的自定义函数。
下面是个最简单的自定义函数,打印一个空行
void newline(void){
 print ("/n");          
}
然后我们在主函数里面调用它,看下效果,首先新建一个文件,two.c:
[root@localhost ~]# vi two.c
#include <stdio.h>
void newline(void){
        printf("\n");
}
int main(void){
        printf("first line.\n");
        newline();
        printf("second line.\n");
        return 0;
}
~
"two.c" [New] 12L, 152C written
[root@localhost ~]# gcc two -o two.c
gcc: two:没有那个文件或目录
gcc: 没有输入文件
[root@localhost ~]# gcc two.c -o two
[root@localhost ~]# ./two
first line.
second line.
[root@localhost ~]#

 
 
        我们可以看到效果,newline的函数功能就是打印一行空行。
函数除了可以被主函数调用之外,也可以被其他函数调用,上面的程序是需要打印一个空行,所以我们写了个函数newline来完成这个
功能,现在假如我们程序中需要经常空3个空行,这个功能如何来实现呢,当然,我们可以用
   printf(“\n”);
   printf(“\n”);
   printf(“\n”);
   来完成,那么是否可以通过调用newline函数来完成这个功能呢,当然是可以的,不过我们还需要自定义另外一个函数threeline;
下面是代码:
[root@localhost ~]# vi three.c 
#include <stdio.h>
/**nweline函数*/
void newline(void){
        printf ("\n");          /**打印一个空格*/
}
/**threeline函数,功能时打印3行空格*/
void threeline(void){
        newline();    /**调用三次,打印三个空行*/
        newline();
        newline();
}
int main(void){
        printf ("the first line.\n");
        newline();                                     /**打印1行空格*/
        printf ("the another three lines.\n");
        threeline();       /**打印3行空格*/
        printf("last line.\n");
        return 0;
}
 
~
"three.c" 20L, 346C written
[root@localhost ~]# gcc three.c -o three
[root@localhost ~]# ./three 
the first line.
the another three lines.
 
last line.
[root@localhost ~]#

      
 
          通过上面的例子我们可以知道同一个函数可以被多次调用,可以用一个函数调用另一个函数,后者再去调第三个函数,呵呵,很简单吧,让我们自己快点动手来写自己的函数吧。。。
本文转自你是路人甲还是霍元甲博客51CTO博客,原文链接http://blog.51cto.com/world77/328332如需转载请自行联系原作者

world77