




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
Chapter4.FunctionandProgramStruction4.1BasicsofFunctionsFormoffunctiondefinition:
return-typefunction-name(argumentdeclaration) { declarationsandstatements } aminimalfunction:dummy(){} returnstatement: returnexpression: or return(expression):4.1BasicofFunctionsExample: #include<stdio.h> #defineMAXLINE1000/*maximuminputlinelength*/ intgetline(charline[],intmax); intstrindex(charsource[],charsearchfor[]); charpattern[]=“ould”;/*patterntosearchfor*/ /*findalllinesmatchingpattern*/ main() {charline[MAXLINE]; intfound=0; while(getline(line,MAXLINE)>0) if(strindex(line,pattern)>=0){ printf(“%s”,line); found++; } returnfound; }4.1BasicofFunctions/*getline:getlineintos,returnlength*/int
getline(chars[],int
lim){intc,i; i=0; while(--lim>0&&(c=getchar())!=EOF&&c!=‘\n’)
s[i++]=c; if(c==‘\n’)s[i++]=c;
s[i]=‘\0’; returni;}/*strindex:returnindexoftins,-1ifnone*/int
strindex(chars[],chart[]){ inti,j,k;
for(i=0;s[i]!=‘\0’;i++){
for(j=i,k=0;t[k]!=‘\0’&&s[j]==t[k];j++,k++); if(k>0&&t[k]==‘\0’)return; } return-1;}4.2FunctionsReturningNon-integersmustdeclarethetypeofvalueitreturnsthecallingroutinemustknowthatreturnsanon-intvalue.example:
#include<ctype.h> /*atof:convertstringstodouble*/ doubleatof(chars[]) { doubleatof(chars[]) inti,sign; for(i=0;isspace(s[i]);i++);/*skipwhitespace*/ sign=(s[i]==‘-’)?-1:1; if(s[i]==‘+’||s[i]==‘-’)i++;for(val=0.0;isdigit(s[i]);i++) val=10.0*val+(s[i]-’0’);if(s[i]==‘.’)i++; for(power=1.0;isdigit(s[i]);i++){ val=10.0*val+(s[i]-’0’); power*=10.0; } returnsign*val/power;
}4.2FunctionsReturningNon-integerscallingatof():declaration(functionprotype) #include<stdio.h> #defineMAXLINE100 main() { doublesum,atof(char[]); charline[MAXLINE];
intgetline(charline[],intmax); sum=0; while(getline(line,MAXLINE)>0) printf(“\t%g\n”,sum+=atof(line)); return0; }callingor:atof();inoldversion4.3ExternalVariablesexternalvariables:definedoutsideofanyfunctionandavailabletomanyfunctions(globallyaccessiable)Example: calculatorthatprovidestheoperators+,-,*/ usereversePolish(逆波蘭)notationinsteadofinfix(中綴). 12-45+*<====>(1-2)*(4+5) themainalgorithmoftheprogram: while(nextoperatororoperandisnotend_of_fileindicator) if(number)
pushit elseif(operator)
popoperands dooperation
pushresult elseif(newline)
popandprinttopofstack elseerror4.3ExternalVariables#include<stdio.h>#include<math.h>#defineMAXOP100/*maxsizeofoperandoroperator*/intgetop(char[]);voidpush(double); /*reversePolishcalculator*/main(){ inttype; doubleop2; chars[MAXOP];
4.3ExternalVariableswhile((type=getop(s))!=EOF){ switch(type){ caseNUMBER:push(atof(s));break; case‘+’:push(pop()+pop());break; case‘*’:push(pop()*pop());
case‘-’:op2=pop();push(pop()-op2);break; case‘/’:op2=pop(); if(op2!=0.0)push(pop()/op2); elseprintf(“error:zerodivisor\n”);break; case‘\n’:printf(“\t.8g\n”,pop());break; default:printf(“erroe:unknowncommand%s\n”,s);break;} } return0;} 4.3ExternalVariables#defineMAXVAL100/*maximumdepthofvalstack*/intsp=0;/*nextfreestackposition*/doubleval[MAXVAL];/*valstack*//*push:pushfontovaluestack*/voidpush(doublef){ if(sp<MAXVAL)val[sp++]=f;elseprintf(‘error:stackfull,can’tpush%g\n”,f);}/*pop:popandreturntopvaluefromstack*/doublepop(void){ if(sp>0)returnval[--sp]; else{printf(“error:stackempty\n”); return0.0; }}4.3ExternalVariables#include<ctype.h>intgetch(void);voidungetch(int);/*getop:getnextoperatorornumericoperand*/intgetop(chars[]){inti,c;while((s[0]=c=getch())==‘‘||c==‘\t’);s[1]=‘\0’;if(!isdigit(c)&&c!=‘.’)returnc;i=0;if(isdigit(c))while(isdigit(s[++i}=c=getch()));if(c==‘.’)while(isdigit(s[++i]=getch()));
s[i]=‘\0’;if(c!=EOF)ungetch(c);returnNUMBER;}4.3ExternalVariables#defineBUFSIZE100charbuf[BUFSIZE];/*bufferforungetch*/intbufp=0;/*nextfreepositioninbuf*/intgetch(void)/*getacharacter*/{ return(bufp>0)?buf[--bufp]:getchar();}voidungetch(intc)/*pushcharacterbackoninput*/{if(bufp>=BUFSIZE)printf(“ungetch:toomanycharacters\n”); elsebufp[bufp++]=c;}Getint與getstr:getch與ungetch的作用#include<stdio.h>charbuf[10];intbp=-1;chargetch(){
if(bp>=0)returnbuf[bp--];elsereturngetchar();}voidungetch(charc){
buf[++bp]=c;}intgetint(){intn=0;charc;while((c=getch())!=EOF){ if(c>='0'&&c<='9')n=n*10+c-'0'; else{ungetch(c);break;}}returnn;}char*getstr(chars[]){inti=0;charc;while((c=getch())!=EOF&&c!='\n'){ if(c>=‘0’&&c<=‘9’)
{ungetch(c);break;} elses[i++]=c;}s[i]='\0';returns;}main(){
inti,j;
chars[20];
i=getint();
getstr(s);
j=getint();
printf("%d%s%d\n",i,s,j);}4.4ScopeRulesscopeofaname(variable,function,ect);
thepartoftheprogramwithinwhichthenamecanbeused.scopeofanautomaticvariable:thefunctioninwhichthenameisdeclaredscopeofanexternalvariableorafunction:
fromthepointatwhichitisdeclaredtotheednofthefileifanexternalvariableistobereferredtobeforeitisdefind oranameisdefindinadifferentsourcefile: anexterndeclarationismandatoryInfile1: Infile2:
externintsp;externdoubleval[];voidpush(doublef){…}voidpop(void){…}intsp=0;doubleval[MAXVAL];4.5HeaderFilesplacethedefinitionsanddeclarationssharedamongthefilesinaheaderfile.example:
calc.h:
#defineNUMBER‘0’voidpush(double);intgetop(char[]);intgetch(void);voidungetch(int);#include<stdio.h>#include<math.h>#include“calc.h”#defineMAXOP100main(){…}#include<stdio.h>#include<ctype.h>#include“calc.h”getop(){…} stack.c:…getch.c…main.c:getop.c:4.6StaticVariablesstatic:(1)appliedtoanexternalvariablesorfunction: limitsthescopeofthatobjecttotherestofthesourcefile,thenameisinvisiableoutsidethefile. staticchar[BUFSIZE];/*bufferforungetch*/intgetch(void){…} voidungetch(intc){…} (2)appliedtoaninternalvariable:
thescopeisthefunction(asautomaticvariable,butitremaininexistenceastheprogram(notthefunction)isactivated.
voidExample(){staticinti=1;printf(“%dtimes\n”,i++);}main(){Example();Example();Example();} result:1times2times3timesstaticvariablesisinitializedonlythefirsttimefunctionisentered4.7RegisterVariablesregister:advisesthecompliertoplacethevariableinregisters,inordertoresultinsmallerandfasterprograms.format registerintx; registercharc;
example: f(registerunsignedm,registerlongn) {registerinti; … }
notice:registerdeclarationcanonlybeappliedtoautomaticvariableandtotheformalparametersofafunctiononlyafewvariablescanbekeptinregisters,excessdeclarationwillbeignored.cannottaketheaddressofaregistervariabletherearerestrictionsontypesofregistervariables.4.8BlockStructureblock:{……}variablecanbedeclaredinablock(followtheleftbrace),,thescopeofthevariableistheblock,andremaininexistenceuntilmatchingtherightbrace.
if(n>0){
inti;/*declareanewi*/for(i=0;i<n;i++)….} thescopeof“i”thevariableininnerscopewillhidevariablesinouterscopeofthesamename.intx,y;f(doublex){doubley;…x=y+1;…}g()…innerfirst4.9Initializationintheabsenceofexplicitinitialization:externalandstaticvariableareinitializedtozeroautomaticandregistervariableshaveundefinedinitialvalueinexplicitinitialization:
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 河北資源環境職業技術學院《中醫飲食保健學》2023-2024學年第一學期期末試卷
- 陜西省寶雞一中學2025年初三第三次模擬練習英語試題含答案
- 南京工業大學《護理研究》2023-2024學年第二學期期末試卷
- 北京朝陽人大附朝陽分校2025年初三下期末聯考(英語試題理)試題含答案
- 無錫商業職業技術學院《國際貿易結算》2023-2024學年第二學期期末試卷
- 川南幼兒師范高等專科學校《工程測試技術》2023-2024學年第二學期期末試卷
- 新疆天山職業技術大學《研學旅行培訓》2023-2024學年第二學期期末試卷
- 游戲產業與電子書出版互動考核試卷
- 2025年度租賃合同模板(標準版)
- 2025年上海市勞動合同范本(官方版)
- 2025念珠菌病診斷和管理全球指南解讀課件
- 碘對比劑應用護理安全性
- 水電站安全生產培訓
- 《礦井提升設備》課件2
- 被迫解除勞動合同通知書電子郵件
- 工具表單-崗位價值評估表(海氏)
- DB33T 2515-2022 公共機構“零碳”管理與評價規范
- 2025年-安徽省安全員知識題庫及答案
- 2024年中國酸奶乳品市場調查研究報告
- 外研版(2025新版)七年級下冊英語Unit 3 學情調研測試卷(含答案)
- 2024重慶市中考語文A卷真題寫作話題解讀與參考范文-漫畫“各有千秋”、“給校長的一封信”
評論
0/150
提交評論