programming in ANSI C-Chapter 9 User-Defined Functions_第1页
programming in ANSI C-Chapter 9 User-Defined Functions_第2页
programming in ANSI C-Chapter 9 User-Defined Functions_第3页
programming in ANSI C-Chapter 9 User-Defined Functions_第4页
programming in ANSI C-Chapter 9 User-Defined Functions_第5页
已阅读5页,还剩47页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Chapter9User-DefinedFunctions,PROGRAMMINGINANSIC,6/13/2020,ModularProgramminginC,Before,thestructureofaCprogramweprogrammedis:,6/13/2020,ModularProgramminginC,Generally,thestructureofCprogramis:,6/13/2020,ModularProgramminginC-ASimpleExample,Writeaprogramtoprintthefollowingoutputs:,print_star()printf(*n);print_message()printf(Howdoyoudo!n);main()print_star();print_message();print_star();,*Howdoyoudo!*,main()printf(*n);printf(Howdoyoudo!n);printf(*n);,6/13/2020,ModularProgramminginC-ClassificationofFunctions,Fromtheperspectiveofuser:Libraryfunctions:printf(),scanf(),sin(),strlen().User-Definedfunctions:print_star().Fromtheperspectiveoftheformoffunctions:Functionswithparameters:printf(Hello),sin(x).Functionswithoutparameter:getchar(),print_star().,6/13/2020,ModularProgramminginC-ClassificationofFunctions,Fromtheperspectiveoftypeoffunctions:Voidfunctions:voidmain().Integerfunctions:printf(),scanf().Doublefunctions:sqrt(x),sin(x).Characterfunctions:getchar().,6/13/2020,intmax(intx,inty)intz;z=xy?x:y;return(z);,FunctionDefinition,Generalformofafunctiondefinition:,function_typefunction_name(parameterlist)DeclarationpartExecutablepart,Ifitisnotexplicitlyspecified,thefunctionwillreturnanintvalue.Ifthefunctiondontreturnanyvalue,itshouldspecifythereturntypeasvoid.,Valididentifier.NoticetoavoidduplicatinglibraryfunctionnamesorOScommands.,FormalparameterslistDeclarevariablesreceivingthedatatransferredbythecallingfunction.Itcanbevoid.,max(intx,inty)intz;z=xy?x:y;return(z);,max(intx,y)intz;z=xy?x:y;return(z);,6/13/2020,print_message()printf(Hello!n);,FunctionDefinition,Generalformofafunctiondefinition:,function_typefunction_name(parameterlist)DeclarationpartExecutablepart,FormalparameterslistDeclarevariablesreceivingthedatatransferredbythecallingfunction.Itcanbevoid.,print_message(void)printf(Hello!n);,Thisfunctionshouldreturnanintvalue.However,itdoesntusereturnstatementtoreturnanyvalue.Insuchcase,itwillreturnanuncertainintvalue.,6/13/2020,print_message()printf(Hello!n);main()printf(%d,print_message();,FunctionDefinition,Generalformofafunctiondefinition:,Hello!7,print_message()printf(Hello!n);return(10);main()printf(%d,print_message();,Hello!10,6/13/2020,voidprint_message()printf(Hello!n);main()printf(%d,print_message();,FunctionDefinition,Generalformofafunctiondefinition:,void:thefunctiondoesntreturnanyvalue.,Error7:Notanallowedtypeinfunctionmain,voidprint_message()printf(Hello!n);main()print_message();,P,voidprint_message()printf(Hello!n);return(10);main()print_message();,Warning3:Voidfunctionsmaynotreturnavaluein,6/13/2020,FunctionParameters,main()inta,b,sum;a=10;b=24;sum=add(a,b);printf(sum=%dn,sum);intadd(intx,inty)intz;z=x+y;return(z);,calladd(10,24),return:z=34,sum=34,main()inta,b,sum;a=10;b=24;sum=add(a,b);printf(sum=%dn,sum);intadd(intx,inty)intz;z=x+y;return(z);,main()inta,b,sum;a=10;b=24;sum=add(a,b);printf(sum=%dn,sum);intadd(inta,intb)intz;z=a+b;return(z);,main()inta,b,sum;a=10;b=24;sum=add(a+b,15);printf(sum=%dn,sum);intadd(inta+b,intb)intz;z=a+b;return(z);,Actualparameterandformalparametercanusethesamename.,Actualparameterscanbevariablesorconstantsorexpressions,butformalparametersmustbevariables.,P,6/13/2020,FunctionParameters,main()inta,b,sum;a=10;b=24;sum=add(a,b);printf(sum=%dn,sum);intadd(intx,inty)x=x+y;return(x);,Actualparameterstransfervaluestoformalparameters,butformalparameterscantinfluenceactualparameters.,a=10,b=24,x=10,y=24,x=34,return34,sum=34,10,24,10,24,34,34,6/13/2020,ReturnValues,Functionsmaysendbackavaluetothecallingfunction,throughthereturnstatement.Function:sendbackthecontrol(maybewithonevalue)tothecallingfucntion.,return(expression);orreturnexpression;orreturn;,6/13/2020,ReturnValues,Functionsmaysendbackavaluetothecallingfunction,throughthereturnstatement.,return(expression);orreturnexpression;orreturn;,intmax(intx,inty)intz;z=xy?x:y;return(z);,intmax(intx,inty)intz;z=xy?x:y;returnz;,intmax(intx,inty)returnxy?x:y;,6/13/2020,ReturnValues,Indefinition,thetypeofthereturnvalueshouldbespecified.Ifitisnotexplicitlyspecified,thereturnvaluedefaultsasinttype.,charletter(charch)floatsum(floatx,floaty)intmax(intx,inty)min(intx,inty),Thetypeofthereturnvalueshouldbeconsistentwiththetypespecifiedinthefunctionheader.,6/13/2020,ReturnValues,Ifthetypeoftheexpressioninreturnstatementdifferswiththetypespecifiedinthefunctionheader,thefunctionvalueissentbackaccordingtothetypespecifiedinthefunctionheader.,max(doublex,doubley)return(xy?x:y);main()printf(%.2f,(float)max(1.0,2.4);,2.4(double),2(int),6/13/2020,ReturnValues,Afunctioncancontainzeroormorethanonereturnstatement.Ifafunctionhasnoanyreturnstatement,itwillreturntothecallingfunctionwhenitencounter.,f(intx)printf(Hello!n);main()printf(%d,f(10);,Hello!7,Thefunctionfwillreturnanuncertainintvalue.,6/13/2020,ReturnValues,Ifafunctionhasmorethanonereturnstatement,itwillreturntothecallingfunctionwhenitencounterthefirstreturnstatement.,f(intx)return(x);printf(Hello!n);return(0);main()printf(%d,f(10);,10,Thecompilerwillproduceawarning.,Warning3:Unreachablecodeinfunctionf,6/13/2020,ReturnValues,Ifafunctiondoesntreturnanyvalue,weshouldspecifyvoidtypeinfunctionheader.,voidprint_message()printf(Hello!n);main()print_message();,voidprint_message()printf(Hello!n);main()printf(%d,print_message();,Thecompilerwillproduceanerror!,Error7:Notanallowedtypeinfunctionmain,6/13/2020,FunctionCalls,Form:function_name(actualparameterlist)Theactualparametersmustmatchthefunctionsformalparametersintype,orderandnumber.Theevaluationorderoftheactualparameterlistisdeterminedbydifferenttools.TheorderinturboCisfromrighttoleft.,6/13/2020,FunctionCalls,intf(inta,intb)intc;printf(%d,%dn,a,b);if(ay?x:y);,6/13/2020,FunctionDeclaration,main()max(intx,inty);inta=10,b=24;printf(%d,max(a,b);max(intx,inty)return(xy?x:y);,Error2:ExpressionsyntaxinfunctionmainError3:ExpressionsyntaxinfunctionmainError4:UndefinedsymbolainfunctionmainError4:Undefinedsymbolbinfunctionmain,main()intmax(intx,inty);inta=10,b=24;printf(%d,max(a,b);max(intx,inty)return(xy?x:y);,intmax(intx,inty);main()inta=10,b=24;printf(%d,max(a,b);max(intx,inty)return(xy?x:y);,6/13/2020,FunctionDeclaration,Beforecalled,theuser-definedfunctionsmustbedeclared,exceptsuchcases:Thefunctiontypeisint.Thedefinitionofthecalledfunctioniswritteninfrontofthecallingfunction.,6/13/2020,FunctionDeclaration,Thefunctiontypeisint.Thecompilerregardsthefunctionformwhichitencountersfirstasthefunctiondeclaration,anddefaultsthefunctiontypeasint.,main()intmax(intx,inty);inta=10,b=24;printf(%d,max(a,b);max(intx,inty)return(xy?x:y);,main()inta=10,b=24;printf(%d,max(a,b);max(intx,inty)return(xy?x:y);,Ifthecalledfunctiontypeisint,itmaynotbedeclared.,6/13/2020,FunctionDeclaration,Thedefinitionofthecalledfunctioniswritteninfrontofthecallingfunction.Thecompilerregardsthefunctionformwhichitencountersfirstasthefunctiondeclaration.Therefore,thecompilermakesthecorrectnesscheckingtothecalledfunctionaccordingtothefunctionheaderinthefunctiondefinition.,main()doublemax(double,double);doublea=10.5,b=24.3;printf(%f,max(a,b);doublemax(doublex,doubley)return(xy?x:y);,main()doublea=10.5,b=24.3;printf(%f,max(a,b);doublemax(doublex,doubley)return(xy?x:y);,Error8:Typemismatchinredeclarationofmax,doublemax(doublex,doubley)return(xy?x:y);main()doublea=10.5,b=24.3;printf(%f,max(a,b);,Ifthedefinitionofthecalledfunctioniswritteninfrontofthecallingfunction,thecalledfunctionmaynotbedeclared.,6/13/2020,FunctionsandArrays,ArrayelementsasparametersvaluetransferringArraynameasparametersaddresstransferring,6/13/2020,FunctionsandArrays-Program1,Comparetwointegerarraysaandb,bothwith6elements.Weusevariablesn,mandktorecordthenumberofaibi,ai=bi,andaik,regardarrayab;Ifnk,regardarrayab;Ifn=k,regardarraya=b.,6/13/2020,FunctionsandArrays-Program2,Calculatetheaveragescoreofthe10students.Read10scoresintofloatarrayscore.Callfunctionaveragetocalculatetheaveragescore.,6/13/2020,FunctionsandArrays-Program2,floataverage(floatstu,intn)floatav,total=0;inti;for(i=0;in;i+)total=total+stui;av=total/n;return(av);main()floatscore10,av;inti;printf(Input10scores:n);for(i=0;i10;i+)scanf(%f,floataverage(floatstu1,intn)floatav,total=0;inti;for(i=0;in;i+)total=total+stui;av=total/n;return(av);main()floatscore10,av;inti;printf(Input10scores:n);for(i=0;i10;i+)scanf(%f,stu=score(sendthestartaddressofarrayscoretostu)n=10,Informalparameters,thearraymaybespecifiedthesize,butithasnoanymeaning.Thecompilerjusttransferstheaddresstotheformalparameter.Therefore,wemusttransferthesizeofarraytoformalparametern,6/13/2020,FunctionsandArrays-Program2,floataverage(floatstu,intn)floatav,total=0;inti;for(i=0;i1,ifwewanttocalculaten!,wemustcalculate(n-1)!first.,6/13/2020,Recursion-Program,main()longfac(int);intn;scanf(%d,6/13/2020,Recursion-Program,fac(4),fac(3),return(24);,1,fac(3),fac(2),return(6);,2,fac(2),fac(1),return(2);,3,fac(1),if(n=0|n=1),f=1;,return(1);,4,6/13/2020,LocalVariablesandGlobalVariables,Localvariables(Alsoknownasinternalvariables)Theyaredeclaredinsideafunction,andcanonlybeusedinthisfunction.Theyarecreatedwhenthisfunctioniscalled,anddestroyedautomaticallywhenthisfunctionisexited.Globalvariables(Alsoknownasexternalvariables)Theyaredeclaredoutsideallfunctions,andcanbeaccessedbythefollowingfunctionsinthisprogram.Itseffectiverangeisfromthedeclarationtotheendoftheprogramfile.,6/13/2020,LocalVariables,floatf1(inta)intb,c;.charf2(intx,inty)inti,j;main()intm,n;.,Formalparametersarelocalvariables.,6/13/2020,LocalVariables,main()inta,b;a=3;b=4;printf(main:a=%d,b=%dn,a,b);sub();printf(main:a=%d,b=%dn,a,b);sub()inta,b;a=6;b=7;printf(sub:a=%d,b=%dn,a,b);,main:a=3,b=4sub:a=6,b=7main:a=3,b=4,6/13/2020,LocalVariables,main()inta,b;a=3;b=4;printf(main:a=%d,b=%dn,a,b);inta,b;a=6;b=7;printf(com:a=%d,b=%dn,a,b);printf(main:a=%d,b=%dn,a,b);,main:a=3,b=4sub:a=6,b=7main:a=3,b=4,Thevariables,declaredinacompoundstatement,canonlybeusedinthiscompoundstatement.,6/13/2020,GlobalVariables,Globalvariables(Alsoknownasexternalvariables)Theyaredeclaredoutsideallfunctions,andc

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论