Typedef function pointer? - c++ - Stack Overflow

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

Understanding typedefs for function pointers in C Resultsfromthe2022DeveloperSurveyarenowavailable Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Typedeffunctionpointer? AskQuestion Asked 11years,7monthsago Modified 8monthsago Viewed 518ktimes 532 223 I'mlearninghowtodynamicallyloadDLL'sbutwhatIdon'tunderstandisthisline typedefvoid(*FunctionFunc)(); Ihaveafewquestions.IfsomeoneisabletoanswerthemIwouldbegrateful. Whyistypedefused? Thesyntaxlooksodd;aftervoidshouldtherenotbeafunctionnameorsomething?Itlookslikeananonymousfunction. Isafunctionpointercreatedtostorethememoryaddressofafunction? SoI'mconfusedatthemoment;canyouclarifythingsforme? c++cpointerstypedef Share Follow editedMay17,2019at7:26 Claudio 10.2k33goldbadges2929silverbadges7070bronzebadges askedNov28,2010at4:50 JackHarvinJackHarvin 6,27577goldbadges2222silverbadges2121bronzebadges 5 5 Takealookatthelink(lastsection)learncpp.com/cpp-tutorial/78-function-pointers – enthusiasticgeek May3,2013at3:28 20 Shouldbenotedthatsincec++11usingFunctionFunc=void(*)();canbeusedinstead.Itisabitmoreclearthatyouarejustdeclaringanameforatype(pointertofunction) – user362515 Jan8,2016at11:55 justtoaddto@user362515,abitclearerformtomeis:usingFunctionFunc=void(void); – topspin May28,2016at21:15 3 @topspinIIRCthesetwoarenotthesame.Oneisafunctionpointertype,theotherisfunctiontype.Thereisimplicitconversion,that'swhyitworks,IANA(C++)Lso,onecanstepinandcorrectme.Inanycase,iftheintendistodefineapointertypeIthinkthesyntaxwiththe*isabitmoreexplicit. – user362515 May31,2016at18:11 HereisarelatedquestionIaskedalongtimeagoaboutwhybothmyFuncPtr()and(*myFuncPtr)()arebothvalidfunctioncalls. – GabrielStaples Feb5at2:01 Addacomment  |  6Answers 6 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 552 typedefisalanguageconstructthatassociatesanametoatype. Youuseitthesamewayyouwouldusetheoriginaltype,forinstance typedefintmyinteger; typedefchar*mystring; typedefvoid(*myfunc)(); usingthemlike myintegeri;//isequivalenttointi; mystrings;//isthesameaschar*s; myfuncf;//compileequallyasvoid(*f)(); Asyoucansee,youcouldjustreplacethetypedefednamewithitsdefinitiongivenabove. ThedifficultyliesinthepointertofunctionssyntaxandreadabilityinCandC++,andthetypedefcanimprovethereadabilityofsuchdeclarations.However,thesyntaxisappropriate,sincefunctions-unlikeothersimplertypes-mayhaveareturnvalueandparameters,thusthesometimeslengthyandcomplexdeclarationofapointertofunction. Thereadabilitymaystarttobereallytrickywithpointerstofunctionsarrays,andsomeotherevenmoreindirectflavors. Toansweryourthreequestions Whyistypedefused? Toeasethereadingofthecode-especiallyforpointerstofunctions,orstructurenames. Thesyntaxlooksodd(inthepointertofunctiondeclaration) Thatsyntaxisnotobvioustoread,atleastwhenbeginning.Usingatypedefdeclarationinsteadeasesthereading Isafunctionpointercreatedtostorethememoryaddressofafunction? Yes,afunctionpointerstorestheaddressofafunction.Thishasnothingtodowiththetypedefconstructwhichonlyeasethewriting/readingofaprogram;thecompilerjustexpandsthetypedefdefinitionbeforecompilingtheactualcode. Example: typedefint(*t_somefunc)(int,int); intproduct(intu,intv){ returnu*v; } t_somefuncafunc=&product; ... intx2=(*afunc)(123,456);//callproduct()tocalculate123*456 Share Follow editedOct10,2021at8:22 Yun 2,53166goldbadges77silverbadges2626bronzebadges answeredNov28,2010at5:13 DéjàvuDéjàvu 27.2k55goldbadges7070silverbadges9797bronzebadges 12 7 inthelastexample,wouldn'tjust'square'refertothesamethingi.epointertothefunctioninsteadofusing&square. – pranavk Mar5,2013at13:32 3 Question,inyourfirsttypedefexampleyouhaveoftheformtypedeftypealiasbutwithfunctionpointersthereonlyseemstobe2arguments,typedeftype.Isaliasdefaultedtothenamespecifiedintypeargument? – dchhetri May3,2013at3:56 3 @pranavk:Yes,squareand&square(and,indeed,*squareand**square)allrefertothesamefunctionpointer. – JonathanLeffler May3,2013at3:58 9 @user814628:Itisnotclearquitewhatyou'reasking.Withtypedefintnewname,youaremakingnewnameintoanaliasforint.Withtypedefint(*func)(int),youaremakingfuncintoanaliasforint(*)(int)—apointertofunctiontakinganintargumentandreturninganintvalue. – JonathanLeffler May3,2013at4:01 13 IguessI'mjustconfusedabouttheordering.Withtypedefint(*func)(int),Iunderstandthatfuncisanalias,justalittleconfusedbecausethealiasistangledwiththetype.GoingbytypedefintINTasanexampleIwouldbemoreofeaseiftypedeffunctionpointerwasofformtypedefint(*function)(int)FUNC_1.ThatwayIcanseethetypeandaliasintwoseparatetokeninsteadofbeingmeshedintoone. – dchhetri May3,2013at5:07  |  Show7morecomments 213 typedefisusedtoaliastypes;inthiscaseyou'realiasingFunctionFunctovoid(*)(). Indeedthesyntaxdoeslookodd,havealookatthis: typedefvoid(*FunctionFunc)(); //^^^ //returntypetypenamearguments No,thissimplytellsthecompilerthattheFunctionFunctypewillbeafunctionpointer,itdoesn'tdefineone,likethis: FunctionFuncx; voiddoSomething(){printf("Hellothere\n");} x=&doSomething; x();//prints"Hellothere" Share Follow editedJul26,2018at17:42 lineil 91011goldbadge88silverbadges1010bronzebadges answeredNov28,2010at4:57 JacobRelkinJacobRelkin 157k3131goldbadges340340silverbadges317317bronzebadges 1 29 typedefdoesnotdeclareanewtype.youcanhavemanytypedef-definednamesofthesametype,andtheyarenotdistinct(e.g.wrt.overloadingoffunctions).therearesomecircumstancesinwhich,withrespecttohowyoucanusethename,atypedef-definednameisnotexactlyequivalenttowhatit'sdefinedas,butmultipletypedef-definednamesforthesame,areequivalent. – Cheersandhth.-Alf Nov28,2010at5:00 Addacomment  |  37 Withoutthetypedefword,inC++thedeclarationwoulddeclareavariableFunctionFuncoftypepointertofunctionofnoarguments,returningvoid. WiththetypedefitinsteaddefinesFunctionFuncasanameforthattype. Share Follow editedMar24,2015at13:57 BartoszKP 33.5k1313goldbadges100100silverbadges127127bronzebadges answeredNov28,2010at4:58 Cheersandhth.-AlfCheersandhth.-Alf 139k1515goldbadges200200silverbadges316316bronzebadges 0 Addacomment  |  18 IfyoucanuseC++11youmaywanttousestd::functionandusingkeyword. usingFunctionFunc=std::function; Share Follow answeredSep21,2017at8:20 HalilKaskavalciHalilKaskavalci 1,9201919silverbadges2929bronzebadges 1 2 withoutC++11usingkeywordwouldbeliketypedefstd::functionFunctionFunc;,justincasesomeonewantsanotherwrapperaroundfunctionswithoutC++11 – Top-Master Mar11,2019at4:25 Addacomment  |  3 #include #include /* Todefineanewtypenamewithtypedef,followthesesteps: 1.Writethestatementasifavariableofthedesiredtypewerebeingdeclared. 2.Wherethenameofthedeclaredvariablewouldnormallyappear,substitutethenewtypename. 3.Infrontofeverything,placethekeywordtypedef. */ //typedefaprimitivedatatype typedefdoubledistance; //typedefstruct typedefstruct{ intx; inty; }point; //typedefanarray typedefpointpoints[100]; pointsps={0};//psisanarrayof100point //typedefafunction typedefdistance(*distanceFun_p)(point,point);//TYPE_DEFdistanceFun_pTOBEint(*distanceFun_p)(point,point) //prototypeafunction distancefindDistance(point,point); intmain(intargc,charconst*argv[]) { //delcareafunctionpointer distanceFun_pfunc_p; //initializethefunctionpointerwithafunctionaddress func_p=findDistance; //initializetwopointvariables pointp1={0,0},p2={1,1}; //callthefunctionthroughthepointer distanced=func_p(p1,p2); printf("thedistanceis%f\n",d); return0; } distancefindDistance(pointp1,pointp2) { distancexdiff=p1.x-p2.x; distanceydiff=p1.y-p2.y; returnsqrt((xdiff*xdiff)+(ydiff*ydiff)); } Share Follow answeredJan11,2017at22:24 AmjadAmjad 2,42022goldbadges1515silverbadges1818bronzebadges 4 1 Underwhatcircumstancesisthe'&'needed?Forexample,do'func_p=&findDistance'and'func_p=findDistance'workequallywell? – Donna Oct30,2017at14:06 1 Afunctionnameisapointer,soyoudonotneedtouse'&'withit.Inotherwords,'&'isoptionalwhenfunctionpointersareconsidered.However,forprimitivedatatypeyouneedtousethe'&'togetitsaddress. – Amjad Oct30,2017at16:41 1 Ithasjustalwaysstruckasoddthatthe'&'caneverbeoptional.Ifatypedefisusedtocreateapointertoaprimitive(i.e.typedef(*double)p,isthe'&'optional? – Donna Oct31,2017at17:39 Ithinkyouwantedtotypetypedefdouble*ptodefineapointertoadouble.Ifyouwanttopopulatetheppointerfromaprimitivevariable,youwillneedtousethe'&'.Asidenote,weyou*todereferenceapointer.The*isusedinthefunctionpointertodereferencethepointer(functionname)andgototheblockofmemorywherethefunctioninstructionsarelocated. – Amjad Oct31,2017at20:16 Addacomment  |  2 ForgeneralcaseofsyntaxyoucanlookatannexAoftheANSICstandard. IntheBackus-Naurformfromthere,youcanseethattypedefhasthetypestorage-class-specifier. Inthetypedeclaration-specifiersyoucanseethatyoucanmixmanyspecifiertypes,theorderofwhichdoesnotmatter. Forexample,itiscorrecttosay, longtypedeflonga; todefinethetypeaasanaliasforlonglong.So,tounderstandthetypedefontheexhaustiveuseyouneedtoconsultsomebackus-naurformthatdefinesthesyntax(therearemanycorrectgrammarsforANSIC,notonlythatofISO). Whenyouusetypedeftodefineanaliasforafunctiontypeyouneedtoputthealiasinthesameplacewhereyouputtheidentifierofthefunction.InyourcaseyoudefinethetypeFunctionFuncasanaliasforapointertofunctionwhosetypecheckingisdisabledatcallandreturningnothing. Share Follow editedMay17,2019at6:43 answeredMay14,2019at8:50 alinsoaralinsoar 14.8k44goldbadges5353silverbadges6868bronzebadges Addacomment  |  Highlyactivequestion.Earn10reputation(notcountingtheassociationbonus)inordertoanswerthisquestion.Thereputationrequirementhelpsprotectthisquestionfromspamandnon-answeractivity. Nottheansweryou'relookingfor?Browseotherquestionstaggedc++cpointerstypedeforaskyourownquestion. TheOverflowBlog Askedandanswered:theresultsforthe2022Developersurveyarehere! LivingontheEdgewithNetlify(Ep.456) FeaturedonMeta Testingnewtrafficmanagementtool Upcomingcleanupofduplicatevotes AskWizardTestResultsandNextSteps Trending:Anewanswersortingoption Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Linked 13 Understandingcomplextypedefexpressions -4 C++:Peculiartypedef -1 typedefvoid(*print_type)(constchar*); 0 StrangetypedefdefinitionC++ 1 ProblemsaboutfunctionpointersinC/C++ 0 Pleaseexplainthisuseoftypedef 0 Whatisthesyntaxinthistypedefstatementdoing? 1 HowcanIreadthisCcode? -1 explanationofthiscomplextypedef 1 what'sthemeaningof"typedefvoid(*__handler)(int)"? Seemorelinkedquestions Related 3713 WhatarethedifferencesbetweenapointervariableandareferencevariableinC++? 2059 WhatisasmartpointerandwhenshouldIuseone? 500 WhyshouldwetypedefastructsoofteninC? 917 Differencebetween'struct'and'typedefstruct'inC++? 1105 WhatisatypedefenuminObjective-C? 1421 HowdofunctionpointersinCwork? 645 Whatdoes"dereferencing"apointermean? 1127 Whatisthedifferencebetween'typedef'and'using'inC++11? 1811 WhyshouldIuseapointerratherthantheobjectitself? HotNetworkQuestions HowcanIrecovermylosttimeinmycareer? Friendlookingtoreturntostudywithouttransferringanycredits IssoundofUSSEnterprise’sautomaticdooropeningindeedtoiletflushingsound? Checkamushroomforest WillRoadstereverencounterMars? Doesthiscountasdeniedentry? FromwhichepisodeofTOSwasthisgifofSpockpullingclothesoutofadresserdrawertaken? AfterthefallofRoevs.Wade,arewomenatriskofcriminalprosecution? Changeinterfacedependingonifstatement Show/miniserieswhichairedonHBOintheearly'90s,featuring"WaterPolice" HowdoImakeaprogramquitwith"q"andrestoretheconsolelike"man"does? GitPushBashscript Whataresomewaystoensurethatacryptographylibraryisreliableinanecosystemthatisnewtome? Whatdoes"CATsthreeandfour"mean? Doescookingfoodinsideapressurecookerandthenleavingitlockedpreserveitsimilartocanning? Floodfillbydistance /var/loghasreached56.6GB.Howtocleanitandmakemorespace? HowtofilterouttheswitchingnoisefromaDC/DCconverter "UnsupportedOS"whenusing`open`commandonM1Pro Ambiguousdeathvsperfectscanner Whydoesthegovernmentnotintroduceanamendmenttotheconstitutiontoallowabortion? Doestheemailsizelimitincludethesizeofthebody? HowcanIremovemarkerswithnumbers2,5,7? ProtectingSmokeAlarmRelayfromLarge(6.5amp@120V)InductiveLoad morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. default Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?