C Language Tutorial => Typedef for Function Pointers

文章推薦指數: 80 %
投票人數:10人

Learn C Language - Typedef for Function Pointers. ... This modified text is an extract of the original Stack Overflow Documentation created by following ... DownloadCLanguage(PDF) CLanguage GettingstartedwithCLanguage BestCProgrammingCourses AwesomeBook AwesomeCommunity AwesomeTutorial AwesomeYouTube —characterclassification&conversion Aliasingandeffectivetype Arrays Assertion Atomics Bit-fields Boolean Command-linearguments Comments CommonCprogrammingidiomsanddeveloperpractices Commonpitfalls Compilation CompoundLiterals Constraints Createandincludeheaderfiles DataTypes DeclarationvsDefinition Declarations Enumerations Errorhandling FilesandI/Ostreams FormattedInput/Output FunctionParameters FunctionPointers Genericselection IdentifierScope Implementation-definedbehaviour ImplicitandExplicitConversions Initialization Inlineassembly Inlining InterprocessCommunication(IPC) IterationStatements/Loops:for,while,do-while JumpStatements Linkedlists Literalsfornumbers,charactersandstrings Memorymanagement Multi-CharacterCharacterSequence Multithreading Operators Pass2D-arraystofunctions Pointers PreprocessorandMacros RandomNumberGeneration SelectionStatements Sequencepoints SideEffects Signalhandling StandardMath StorageClasses Strings Structs StructurePaddingandPacking Testingframeworks Threads(native) TypeQualifiers Typedef SimpleUsesofTypedef TypedefforFunctionPointers TypedefforStructuresandUnions Undefinedbehavior Unions Valgrind Variablearguments X-macros CLanguage GettingstartedwithCLanguage BestCProgrammingCourses AwesomeBook AwesomeCommunity AwesomeTutorial AwesomeYouTube —characterclassification&conversion Aliasingandeffectivetype Arrays Assertion Atomics Bit-fields Boolean Command-linearguments Comments CommonCprogrammingidiomsanddeveloperpractices Commonpitfalls Compilation CompoundLiterals Constraints Createandincludeheaderfiles DataTypes DeclarationvsDefinition Declarations Enumerations Errorhandling FilesandI/Ostreams FormattedInput/Output FunctionParameters FunctionPointers Genericselection IdentifierScope Implementation-definedbehaviour ImplicitandExplicitConversions Initialization Inlineassembly Inlining InterprocessCommunication(IPC) IterationStatements/Loops:for,while,do-while JumpStatements Linkedlists Literalsfornumbers,charactersandstrings Memorymanagement Multi-CharacterCharacterSequence Multithreading Operators Pass2D-arraystofunctions Pointers PreprocessorandMacros RandomNumberGeneration SelectionStatements Sequencepoints SideEffects Signalhandling StandardMath StorageClasses Strings Structs StructurePaddingandPacking Testingframeworks Threads(native) TypeQualifiers Typedef SimpleUsesofTypedef TypedefforFunctionPointers TypedefforStructuresandUnions Undefinedbehavior Unions Valgrind Variablearguments X-macros CLanguage Typedef TypedefforFunctionPointers Example Wecanusetypedeftosimplifytheusageoffunctionpointers.Imaginewehavesomefunctions,allhavingthesamesignature,thatusetheirargumenttoprintoutsomethingindifferentways: #include voidprint_to_n(intn) { for(inti=1;i<=n;++i) printf("%d\n",i); } voidprint_n(intn) { printf("%d\n,n); } Nowwecanuseatypedeftocreateanamedfunctionpointertypecalledprinter: typedefvoid(*printer_t)(int); Thiscreatesatype,namedprinter_tforapointertoafunctionthattakesasingleintargumentandreturnsnothing,whichmatchesthesignatureofthefunctionswehaveabove.Touseitwecreateavariableofthecreatedtypeandassignitapointertooneofthefunctionsinquestion: printer_tp=&print_to_n; void(*p)(int)=&print_to_n;//Thiswouldberequiredwithoutthetype Thentocallthefunctionpointedtobythefunctionpointervariable: p(5);//Prints12345onseparatelines (*p)(5);//Sodoesthis Thusthetypedefallowsasimplersyntaxwhendealingwithfunctionpointers.Thisbecomesmoreapparentwhenfunctionpointersareusedinmorecomplexsituations,suchasargumentstofunctions. Ifyouareusingafunctionthattakesafunctionpointerasaparameterwithoutafunctionpointertypedefinedthefunctiondefinitionwouldbe, voidfoo(void(*printer)(int),inty){ //code printer(y); //code } However,withthetypedefitis: voidfoo(printer_tprinter,inty){ //code printer(y); //code } Likewisefunctionscanreturnfunctionpointersandagain,theuseofatypedefcanmakethesyntaxsimplerwhendoingso. Aclassicexampleisthesignalfunctionfrom.Thedeclarationforit(fromtheCstandard)is: void(*signal(intsig,void(*func)(int)))(int); That'safunctionthattakestwoarguments—anintandapointertoafunctionwhichtakesanintasanargumentandreturnsnothing—andwhichreturnsapointertofunctionlikeitssecondargument. IfwedefinedatypeSigCatcherasanaliasforthepointertofunctiontype: typedefvoid(*SigCatcher)(int); thenwecoulddeclaresignal()using: SigCatchersignal(intsig,SigCatcherfunc); Onthewhole,thisiseasiertounderstand(eventhoughtheCstandarddidnotelecttodefineatypetodothejob).Thesignalfunctiontakestwoarguments,anintandaSigCatcher,anditreturnsaSigCatcher—whereaSigCatcherisapointertoafunctionthattakesanintargumentandreturnsnothing. Althoughusingtypedefnamesforpointertofunctiontypesmakeslifeeasier,itcanalsoleadtoconfusionforotherswhowillmaintainyourcodelateron,sousewithcautionandproperdocumentation.SeealsoFunctionPointers. PDF-DownloadCLanguageforfree Previous Next ThismodifiedtextisanextractoftheoriginalStackOverflowDocumentationcreatedbyfollowingcontributorsandreleasedunderCCBY-SA3.0 ThiswebsiteisnotaffiliatedwithStackOverflow SUPPORT&PARTNERS Advertisewithus Contactus PrivacyPolicy STAYCONNECTED Getmonthlyupdatesaboutnewarticles,cheatsheets,andtricks.  Subscribe



請為這篇文章評分?