lecture 12: pointers to functions...
TRANSCRIPT
Hank Childs, University of OregonNovember 7, 2019
Lecture 12:Pointers to Functions
Complexity
__. __ .__ __. __ ___ ___ ______ ___ .__ __. _______ _______ ___ .___________. ___| | | | | \ | | | | \ \ / / / | / \ | \ | | | \ | \ / \ | | / \| | | | | \| | | | \ V / | ,----' / ^ \ | \| | | .--. | | .--. | / ^ \ `---| |----` / ^ \| | | | | . ` | | | > < | | / /_\ \ | . ` | | | | | | | | | / /_\ \ | | / /_\ \| `--' | | |\ | | | / . \ __ | `----.__ / _____ \ | |\ | | '--' | | '--' | / _____ \ | | / _____ \\______/ |__| \__| |__| /__/ \__\ (_ ) \______(_ ) /__/ \__\ |__| \__| |_______/ |_______/ /__/ \__\ |__| /__/ \__\
_______.___________..______ __ __ ______ .___________. __ __ .______ _______ _______. / | || _ \ | | | | / || || | | | | _ \ | ____| / | | (----`---| |----`| |_) | | | | | | ,----'`---| |----`| | | | | |_) | | |__ | (----` \ \ | | | / | | | | | | | | | | | | | / | __| \ \
.----) | | | | |\ \----.| `--' | | `----. | | | `--' | | |\ \----.| |____.----) ||_______/ |__| | _| `._____| \______/ \______| |__| \______/ | _| `._____||_______|_______/
TalkaboutQ1frommidterm
Project2G
QuizonTuesday,Nov12
• TherewillbeaquizTuesdayNov12.• Itwillbeworth3points.• ItwillbeonfileI/O.• Nonotes.• Expectingyoutoknowfopen/fread/fwrite/etc.
Reading:Chapters5and6
• Iwillbefollowingthetextbookmorecloselythenextfewweeks
Callbyvalue/callbyreference
• Referstohowparametersarepassedtoafunction.– Callbyvalue:sendthevalueofthevariableasafunctionparameter• Sideeffectsinthatfunctiondon’t affectthevariableinthecallingfunction
– Callbyreference:sendareference(pointer)asafunctionparameter• Sideeffectsinthatfunctionaffectthevariableinthecallingfunction
CallbyValue
Cdoesnotcarethatfoohasan
argumentvariablecalled“x”andmainhasan
automaticvariablecalled“x”.TheyhaveNOrelation.
Callbyreference
Preprocessor
• Preprocessor:– takesaninputprogram– producesanotherprogram(whichisthencompiled)
• Chasaseparatelanguageforpreprocessing– DifferentsyntaxthanC– Usesmacros(“#”)
macro(“macroinstruction”):ruleforreplacinginputcharacterswithoutputcharacters
#include
• compilercanonlycompileonefileatafile• takesanotherfileandincludesitinthecurrentfile
• thefileisa“header”file– itcontainsfunctionprototypes– afunctionprototypedeclaresafunctionexists,butnothowitisimplemented
Demonstrate#include
#include<stdio.h>int main(){printf("Helloworld\n");
}
%gcc –Eprintf.c
FunctionPrototype
PreprocessorPhases
• Resolve#includes• Conditionalcompilation(#ifdef)• Macroreplacement• Specialmacros
#definecompilation
Thisisanexampleofmacroreplacement.
#defineviagcc command-lineoption
Conflicting–Dand#define
Conditionalcompilation
Conditionalcompilationcontrolledviacompilerflags
FunctionPointers
• Idea:– Youhaveapointertoafunction– Thispointercanchangebasedoncircumstance–Whenyoucallthefunctionpointer,itislikecallingaknownfunction
FunctionPointerExample
FunctionPointerExample#2
Functionpointer Partoffunctionsignature
Don’tbescaredofextra‘*’s…theyjustcomeaboutbecauseofpointersintheargumentsorreturnvalues.
Simple-to-ExoticFunctionPointerDeclarations
void(*foo)(void);void(*foo)(int **,char***);char**(*foo)(int **,void(*)(int));
Thesesometimescomeuponinterviews.
FunctionPointersvs Conditionals
Whataretheprosandconsofeachapproach?
Callbacks
• Callbacks:functionthatiscalledwhenaconditionismet– Commonlyusedwheninterfacingbetweenmodulesthatweredevelopedseparately.
– …librariesusecallbacksanddeveloperswhousethelibraries“register”callbacks.
Callbackexample
Callbackexample
WhatisaDataStructure?
WhatisaDataStructure?
• Datastructuredefinitions– Textbook:“asystematicwaytoorganizedata”–Wikipedia:“dataorganization,managementandstorageformatthatenablesefficientaccessandmodification”
WeAreAlreadyFamiliarWithSomeDataStructures
• Arrays• FromPython– List– Tuple– Dictionary– Set
KeyConcept
• Itorganizesdata• Itenablesefficientaccess–Whatdoesefficientmean??
Example:DataStructure:ArraysOperation:Search
IsItEfficient?:TwoSub-questions
• 1)Howlongdoesthistaketorun?– (howdowemeasurethis?)
• 2)Couldwedoitwithlessoperations?
IsItEfficient?:TwoSub-questions
• 1)Howlongdoesthistaketorun?– (howdowemeasurethis?)
• 2)Couldwedoitwithlessoperations?
HowLongDoesThisTakeToRun?
• Oneanswer:timeit!
Unixcommand:time
Courtesy:Sventek textbook
Anotheroption:addtimingstoyourprogram!
• (note:nowtakingafewslideaside)
gettimeofday
(therearelotsofUnixsystemcalls,whichdolotsofdifferentthings)
gettimeofday example
gettimeofday example
gettimeofday example
gettimeofday example
HowLongDoesThisTakeToRun?
• Oneanswer:timeit!• Question:whatifIchangethedata?–Whatifwehave8000studentsinsteadof80students?
• Newidea:analyzetheprogram
AnalyzetheProgram
• Howmanyoperationsdoesthisperform?• Assumestrcmp takes50operations• AndnumStudents is80• Then~80*50=4000operation
BigONotation(1/3):ImportantComputerScienceConcept
• Ifinputdatasizeis“N”,thenyoucandescribehowmanyoperationsoccurusingN
• If“numStudents”isN,andstrcmp takes50operations,then50N
BigONotation(2/3):ImportantComputerScienceConcept
• Idea#1behindBigO:don’tworryaboutconstants• Idea#2behindBigO:justsayhowmanyoperationswithrespecttoN(numberofdataelements)
• Answer:O(N)– Thisissosimple,almostnotuseful… neednewexample!
BigONotation(3/3):ImportantComputerScienceConcept
• Thisiscalled“AsymptoticAnalysis”–Why?… whathappenswhenNgets“large”?
Morecomplexexample
• Howmanyoperationsnow?• numStudents*numStudents*50(about)• à O(n2)
IsThisBetter?
• Howmanyoperationsnow?• numStudents*numStudents*25(about)• STILLà O(n2)
ComparingOurTwoImplementations
• Answer:secondversionisabouttwiceasfast– ButbothO(n2),somaybenotahugedifference
Newdatastructure:sortedarray
• Likeanarray,buteverythingissorted• Unsortedarray– int X[6]={4,1,3,7,9,2};
• Sortedarray– int X[6]={1,2,3,4,7,9};
CanWeImproveOnThisOneWithAnUnsortedArray?
• Probablynot,but…
ButWeCanImproveWithaSortedArray…
Howmanyoperationsdidthistake?
• StartwithNelements• After1iteration,N/2elements• After2iterations,N/4elements• After3iterations,N/8elements• After4iterations,N/16elements• Etc…• Afterlog2Niterations,1element• à O(logn)
Buttherewasworktotakeanarrayandmakeasortedarray
• Howlongdoesittaketosort?• Sort:complexityvaries:O(nlogn)toO(n2)– Project2Bexample:O(n2)– Mostrealworld:O(nlogn)
• So:wecoulddoIsStudentInClass onunsortedarrayforO(n)
• Or:sortarray(costO(nlogn))anddoIsStudentInClass forO(logn)
• à weonlywanttodoasortifweplantocallIsStudentInClass abunchoftimes
CanwegetabetterBigOforthisone?
• ‘for’loopovernumStudents:O(n)• Combined:O(nlogn)+O(n)à O(nlogn)– (asymptoticanalysis)
Courtesy:Sventek textbook
IsItEfficient?:TwoSub-questions
• 1)Howlongdoesthistaketorun?– (howdowemeasurethis?)
• 2)Couldwedoitwithlessoperations?
• Unsortedarraysweremoreefficientforsearch,buttherewasworkincreatingthem– Differentdatastructuresareefficientfordifferentoperations
– Hence,wehavealotofthem