函数和流程控制也是每个编程语言的基本概念,函数是划分模块的最小单位,良好的函数规划能直接提升软件的质量,C语言的流程控制主要由以下几个语句组成,条件分支语句、选择语句、循环语句、goto语句、return语句等。

函数的定义

一个函数包含返回值、函数名和参数列表,如下定义了一个返回值为 int 函数名为show拥有一个int类型参数的函数

intshow(intparam){printf("这是一个名为show的函数");return0;}

再来定义个没有返回值,没有参数列表的函数

voidinfo(void){printf("参数列表里的void可以不要");}

函数调用

#include<stdio.h>intshow(intparam){printf("show\n");return0;}voidinfo(void){printf("info\n");}voidmulti_param(inta,intb,intc){printf("多个参数用逗号分割\n");}intmain(intargc,char*argv[]){intresult=show(10);///调用showinfo();///调用infomulti_param(1,2,3);///调用return0;}

条件分支语句

voidshow_score(intscore){if(100==score){printf("满分\n");}}voidshow_score(intscore){if(100==score){printf("满分\n");}else{printf("不是满分\n");}}voidshow_score(intscore){if(score>=90){printf("高分\n");}elseif(score>=60){printf("及格\n");}else{printf("不及格\n");}}

选择语句

voidshow(intvalue){switch(value){case1:printf("one\n");break;case2:printf("two\n");break;case3:printf("three\n");break;default:printf("以上都不满足时,就到此处\n");break;}}

循环语句

voidplus(){inti,total=0;///1+2+3+...+100for(i=1;i<=100;i++){total+=i;}printf("result=%d\n",total);}voidplus(){inti=0,total=0;///1+2+3+...+100while(i<=100){total+=i;i++;}printf("result=%d\n",total);}voidplus(){inti=0,total=0;///1+2+3+...+100do{total+=i;i++;}while(i<=100);printf("result=%d\n",total);}