Typedef function pointer? - c++ - Stack Overflow
文章推薦指數: 80 %
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