11 Pages

lecture12_function_advanced

Course: ECE 206, Fall 2009
School: Tennessee
Rating:
 
 
 
 
 

Word Count: 1216

Document Preview

- ECE206 Programming Lecture 12 Function (Advanced Features) 11/13/07 What do you need to know Fundamentals Function declaration Forward prototype Forward definition Call-by-value vs. callby-reference Command-line arguments Storage class Advanced topics Function overloading Inline functions Functions with default augments * Function templates * Recursive functions * Function pointer 2 1 C++ storage classes -...

Register Now

Unformatted Document Excerpt

Coursehero >> Tennessee >> Tennessee >> ECE 206

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
- ECE206 Programming Lecture 12 Function (Advanced Features) 11/13/07 What do you need to know Fundamentals Function declaration Forward prototype Forward definition Call-by-value vs. callby-reference Command-line arguments Storage class Advanced topics Function overloading Inline functions Functions with default augments * Function templates * Recursive functions * Function pointer 2 1 C++ storage classes - revisit Each C++ variable has several attributes: name, type, size, value storage class, scope, linkage C++ has four storage classes auto: the default. Variables are automatically created and initialized when they are defined and are destroyed at the end of the block containing their definition. They are not visible outside that block. register: a type of auto variable. a suggestion to the compiler to use a CPU register for performance. static: a variable that is known only in the function that contains its definition but is never destroyed and retains its value between calls to that function. It exists from the time the program begins execution. extern: a static variable whose definition and placement is determined when all object and library modules are combined (linked) to form the executable code file. It can be visible outside the file where it is defined. 3 Example - register #include <ctime> register int i, j; int starttime, endtime; starttime = clock() for (i=0; i<LARGENUM; i++) ; endtime = clock(); cout << the duration is << endtime starttime; 4 2 A few more things about register A modern processor normally has at least 32 registers for integer variables and 32 registers for floating point variables Each register is 32 bit or 64 bit depending on different computer architectures An optimized compiler should allocate the most frequently accessed variables in the register with or without explicitly specifying register storage class Theres only limited amount of registers. What if all the registered are occupied? 5 Example static variables // compute a running avg. of numbers entered by user #include <iostream> using namespace std; float r_avg(int i); int main() { int num; } float r_avg(int i) { static float sum = 0 static int count = 0; sum += i; count++; return sum / count; do { cout << Enter numbers (-1 to quit): ; cin >> num; cout << Running average is: << r_avg(num); cout << \n; } while (num > -1); return 0; } 6 3 Another example int Complex::getCount() { return count; } // class definition // method implementation class Complex { Complex::Complex() public: Complex(); { Complex(float, float); real = 0; imag = 0; ~Complex(); void setComplex(float, float); count++; void printComplex(); } float getReal() const; float getImag() const; Complex::Complex(float a, float b) void setReal(float); { void setImag(float); real = a; imag = b; static int getCount(); count++; private: float real; } float imag; Complex::~Complex() static int count; }; } { count--; 7 Inline functions Short frequently used functions are good candidates for inline functions. An inline functions body is inserted directly in the compiled code at the point where the function would normally be called. The advantage is efficiency. Like the register keyword, inline is only a suggestion to the compiler. 8 4 Example // using inline function to calculate the volume of a cube #include <iostream> using namespace std; inline float cube(float s) { return s * s * s; } int main() { float side; cin >> side; cout << The volume of cube with side << side << is << cube(side); return 0; } 9 Default arguments Default arguments have a defined value if they are not present in the calling parameter list. Default argument must be the rightmost parameters (so they can be omitted). Default arguments must be specified only once (first appearance of function name, usually in function prototype). 10 5 Example // inline function definition inline int volume (int length, int width = 1, int height = 1) { return length * width * height; } int main() { int v1, v2, v3; v1 = volume (1,5); // value is 5 v2 = volume // (4); value is 4 v3 = volume (2,2,2); // value is 8 } v1 = 1 * 5 * 1 v2 = 4 * 1 * 1 v3 = 2 * 2 * 2 11 No function call!!! Multiple copies of the function implementation in the object code Function overloading One of C++s most exciting feature C++ allows several functions with the same name to be defined, as long as the types and/or numbers of their arguments differ. The functions that share the same name are said to be overloaded Function overloading is one way that C++ achieves polymorphism 12 6 // overloading abs() #include <iostream> using namespace std; // abs() is overloaded in two ways int abs(int i); double abs(double d); int main() { cout << abs(-10) << \n; cout << abs(-11.0) << \n; return 0; } int abs(int i) { if (i<0) return -i; else return i; } double abs(double d) { if (d<0.0) return -d; else return d; } Example Consider 2 functions located in the standard library: abs(), fabs(). They are first defined by the C language, and for compatibility, are also included in C++. So for similar tasks, programmer has two names to remember, not just one. C++ can resolve this problem by function overloading 13 * Function Templates Function templates allow the definition of functions independent of the type of the arguments and return value. This implements a philosophy of writeonce / use-anywhere by allowing parameterized types. Templates form the basis for the C++ Standard Template Library (STL) of algorithms, which we will discuss later. 14 7 * A Function Template Example int maximum ( int value1, int value2, int value3 ) { int max = value1; if ( value2 > max ) max = value2; if ( value3 > max ) max = value3; return max; } template <class T> T maximum ( T value1, T value2, T value3 ) { T max = value1; if ( value2 > max ) max = value2; if ( value3 > max ) max = value3; return max; } int main() { int a=1,b=3,c=3; int m; m = maximu<int>(a, b, c); return 0; } A list of formal type parameters, preceded by the class keyword, is specified 15 between the <>, and is used in place of types in the function definition. * Recursion Recursive functions calls itself (directly or through another function). Any C++ function call call itself, but functions that use static and extern variables must do so carefully. Recursion can be used to solve problems by induction: Do one step, and call itself to solve the remaining problem. Detect and perform the last step (base case). 16 8 ...

Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

Tennessee - ECE - 206
Questionnaire ECE206 (Fall 2007)1. Name: Department: Major: Email: Level (freshman or sophomore): 2. Which of the following programming languages have you HEARD of? Please circle. (a) C (b) C+ (c) Java (d) Basic (e) C# (f) Pascal3. Which of the
Tennessee - ECE - 206
ECE206 - ProgrammingMidterm Review10/4/07Computer Architecture and programming environmentWhat is a computer? What are the basic components of a von-Neumann machine? What does a compiler do? What does a linker do?What does a loader do? What is
Tennessee - ECE - 206
ECE206 - ProgrammingLecture 3 Operators and Data Type08/30/07RecapProgramming environmentPre-complied lib 000110101 011111000 001010101 *.cpp int main() complier { cout &lt; } *.o 001001010 010010100 010010010 010100101 *.exe 001001010 linker 010
Stanford - ECON - 310
Aggregate Implications of Lumpy Investment: New Evidence and a DSGE ModelRuediger BachmannRicardo J. CaballeroEduardo M.R.A. EngelJune 11, 2008Abstract The sensitivity of U.S. aggregate investment to shocks is procyclical: the initial respo
Stanford - ECON - 310
Risk Matters: The Real Eects of Volatility ShocksJess Fernndez-Villaverde University of Pennsylvania, NBER, and CEPR Pablo Guerrn-Quintana North Carolina State University Juan F. Rubio-Ramrez Duke University and Federal Reserve Bank of Atlanta Martn
W. Alabama - GIMO - 141
1Sonata a Mandolino solo e BassoGiovanni Battista Gervasio (c.1725-c.1785)Gimo 141Allegro4710 1013 1316 1620 20Public Domain224 2428 282 42 432 3235 3538 3841 4144 4447 47Mutopia-2003/06/24-326350 5053
W. Alabama - GIMO - 142
1Sonata Per Camera di Mandolino e BassoGiovanni Battista Gervasio (c.1725-c.1785)Gimo 142Allegro4710 106613 136666 6 6 66 6 66616 16666666 666666619 19666SimilePublic Domain224
W. Alabama - GIMO - 142
1Sonata Per Camera di Mandolino e BassoGiovanni Battista Gervasio (c.1725-c.1785)Gimo 142Allegro4710 106613 136666 6 6 66 6 66616 16666666 666666619 19666SimilePublic Domain224
Indiana - MUSIC - 100
2003-05 SCHOOL OF MUSIC BULLETINThe Artist Diploma is a program for outstanding performers who intend to pursue a career in performance. The program provides for concentrated study in appropriate repertoire. This sheet is for use as an aid in unders
Southern Utah - MUS - 316
Claude Debussy (1862-1918) Influences Music French predecessors / contemporaries, e.g. Franck, Saint-Sans (late Romantic, conservative in style) Wagner - orchestration, chromaticism Russians - e.g. Musorgskys alternative tonal structures Asian mu
W. Alabama - GIMO - 144
1Sonata per Camera di Mandolino e BassoGiovanni Battista Gervasio (c.1725-c.1785)Gimo 144Allegro maestoso4812 1215 1518 18Simi:22 2226 26d.fffPublic Domain230 3034 34d.38 3841 4144 44347 47d.51 51
Indiana - MUSIC - 100
SUMMER MUSIC CLINIC APPLICATION FORM (JUNE 7 - 13, 2009)S tu d e n t G e n e r a l In fo r m a tio n N a m e (L a s t, F ir s t, M id d le ) H om e Phone E -m a il A d d r e s s H o m e A d d re ss C u rre n t A ge N a m e o f R e q u e s te d R o o
USF - EEL - 3394
EEL 3394 Exam 1 Key 1. Fill in the blank with the name of the atomic bond (8 pts). a.) Ionic another. b.) Covalent form when electrons from one atom are transferred to form when electrons are shared between atoms.c.) Metallic form when there is a c
USF - EEL - 3394
EEL 3394 Exam 2 1. Label the band diagrams below (10 pts)a.) Reverse biasb.)Equilibriumc.) Forward bias2. True or False (10 pts) a.) F When a semi-conductor is exposed to light or heat, the resistance will increase. b.) T c.) F d.) F e.) T
USF - EEL - 3394
EEL 3394: Electronic MaterialsInstructor: Office: Phone: E- mail: T A: Office Hours: Course Text: Prerequisites: Course Objective: Stephen E. Saddow, Ph.D. ENB 243 974-4773 saddow@ieee.org Suzie Harvey sharvey4@eng.usf.edu By appointment O NLY S.O.
Indiana - MUSIC - 100
School of Music Indiana UniversityFor students entering the D.M. program in the School of Music: Fall 2003 through Summer 2005Requirements for:Doctor Of Music GuitarCurrent students may obtain an up-to-date degree audit using INSITE, http:/insi
Indiana - MUSIC - 100
School of Music Indiana UniversityFor students entering the D.M. program in the School of Music: Fall 2003 through Summer 2005Requirements for:Doctor Of Music Trumpet and CornetCurrent students may obtain an up-to-date degree audit using INSITE
Indiana - MUSIC - 100
School of Music Indiana UniversityFor students entering the D.M. program in the School of Music: Fall 2001 through Summer 2003Requirements for:Doctor Of Music Woodwinds (5 Instruments)Current students may obtain an up-to-date degree audit using
Indiana - MUSIC - 100
School of Music Indiana UniversityFor students entering the D.M. program in the School of Music: Fall 2006 through Summer 2007Requirements for:Doctor Of Music Woodwinds (5 Instruments)Current students may obtain an up-to-date degree audit using
Indiana - MUSIC - 100
Jacobs School of Music Indiana UniversityFor students entering the D.M. program in the Jacobs School of Music: Fall 2007 through Summer 2009Requirements for:Doctor Of Music HornCurrent students may obtain an up-to-date degree audit using OneSta
Indiana - MUSIC - 100
School of Music Indiana UniversityFor students entering the D.M. program in the School of Music: Fall 2001 through Summer 2003Requirements for:Doctor Of Music Brass Pedagogy (Trombone)Current students may obtain an up-to-date degree audit using
Indiana - MUSIC - 100
School of Music Indiana UniversityFor students entering the D.M. program in the School of Music: Fall 2005 through Summer 2007Requirements for:Doctor Of Music FluteCurrent students may obtain an up-to-date degree audit using OneStart, http:/one
Indiana - MUSIC - 100
School of Music Indiana UniversityFor students entering the D.M. program in the School of Music: Fall 2005 through Summer 2007Requirements for:Doctor Of Music ViolaCurrent students may obtain an up-to-date degree audit using OneStart, http:/one
Ohio State - EE - 351
EE 351 Lecture Packet #1OutlineIntroductionSignals and systemsExample systemsSystem modelsClassication of signalsImportant signalsSystem propertiesCopyright 1998-2003, L.C. Potter The Ohio State UniversityOHIO S ATE T
Indiana - MUSIC - 100
School of Music Indiana UniversityFor students entering the M.M. program in the School of Music: Fall 2005 through Summer 2007Requirements for:Master Of Music EuphoniumCurrent students may obtain an up-to-date degree audit using OneStart, http:
Indiana - MUSIC - 100
School of Music Indiana UniversityFor students entering the M.M. program in the School of Music: Fall 2005 through Summer 2007Requirements for:Master Of Music TromboneCurrent students may obtain an up-to-date degree audit using OneStart, http:/
Indiana - MUSIC - 100
School of Music Indiana UniversityFor students entering the M.M. program in the School of Music: Summer 2006 through Summer 2007Requirements for:Master Of Music Choral ConductingCurrent students may obtain an up-to-date degree audit using OneSt
Indiana - MUSIC - 100
School of Music Indiana UniversityFor students entering the M.M. program in the School of Music: Fall 2005 through Summer 2007Requirements for:Master Of Music Early Music Keyboard/Plucked Instrument EmphasisCurrent students may obtain an up-to
Indiana - MUSIC - 100
Jacobs School of Music Indiana UniversityFor students entering the M.M. program in the Jacobs School of Music: Fall 2007 through Summer 2009Requirements for:Master Of Music VioloncelloCurrent students may obtain an up-to-date degree audit using
Indiana - MUSIC - 100
General Education Requirements for BME majors Total - 27 credit hoursOral and Written Expression (9 credit hours)1. Oral Expression (3 credit hours) Select one of the following (grade of C or better required, can not betaken Pass/Fail or by corres
Southern Utah - ART - 210
Indiana - MUSIC - 100
Indiana University School of Music BME General - Singer 4 Year Year 1 Fall Year 1- Spring Ensemble 2 Ensemble 2 Performance Study 2 Performance Study 2 T151 Music Theory 3 T152 Music Theory 3 General Ed Elective 3 T132 Music Skills 1 General Ed Elec
Ohio State - ECE - 206
Winter 2005EE 206 Switching Circuits Laboratory Course SyllabusInstructor: Tim Hartley Office: DL 805 Office Hours: By appointment only. Email: hartleyt@ece.osu.edu Web Page: http:/www.ece.osu.edu/~hartleyt/ECE206/ Required Text: EE206 notes from
Washington - CEE - 404
TOTAL NORTHBOUND TRAFFIC (MAINLINE + EXPRESS LANES)Hourly directional traffic count 2007 DataThe following table shows the percentage of vehicle traffic occuring during each hour interval for each day of the week Hour of the day (starting at the n
Washington - CEE - 404
EASTBOUNDHourly directional traffic count SR 90, MP 82.7, Near Cle Elum 2007 Data (November and December numbers are from 2006) The following table shows the percentage of vehicle traffic occuring during each hour interval for each day of the week H
San Jose State - HS - 167
3: Summary StatisticsWays to measure distributional characteristicsTypes of Summary Statsp. 3.1P Central location&lt; Mean &lt; Median &lt; ModeP Spread&lt; Variance &amp; standard deviation &lt; Range &amp; inter-quartile rangeP Shape measures not often used
San Jose State - HS - 167
Biostatistics (HS167) Fall 2004 San Jose State University Dept. of Health Science Prerequisite Satisfactory completion of the GE Math (B4) requirement (undergraduates). Website Instructors www.sjsu.edu/biostat The website includes the schedule of top
San Jose State - HS - 167
9: Inference About a Proportionp. 9.1P Recall binomial random variables (Chap 4)&lt; n independent observations &lt; Each observation classified as success or failure (qualitative outcome) &lt; p = probability of success each observation ( parameter p) &lt; X
Cal Poly Pomona - ECE - 308
California State Polytechnic University, PomonaElectrical &amp; Computer Eng. Dr. Zekeriya AliyaziciogluECE 308 - 03 Introduction to Discrete Time Signals &amp; SystemsExam #1Solution Name:_1. Compute and sketch the convolution y(n) of the following si
El Paso CC - ART - 212
Handout 14 Art in the US before World War III. American art in 19th Century: initial predominance of Europe A. John Singer Sargent (1856-1925): Refined and flattering portraits of wealthy sitters. Much of career spent in Europe (especially London)
Purdue - ECON - 512
Economics 512 Spring 2009 Saunders Quiz 3Name: _1. How does the importance of economic growth compare with that of cyclical fluctuations from the point of view of consumers welfare? Although we read about cyclical phenomena much more frequently,
Cal Poly Pomona - EGR - 544
Cal Poly PomonaElectrical &amp; Computer Eng.EGR 544 Communication TheoryHomework #1 Answers Not yet!EGR 544-1
Wesleyan - PHYS - 505
GRADUATE RECORD EXAMINATIONSPhysics TestPractice BookThis practice book containsone actual full-length GRE Physics Test test-taking strategiesBecome familiar withtest structure and content test instructions and answering procedures Compare
Wesleyan - PHYS - 505
This book is provided FREE with test registration by the Graduate Record Examinations Board.Graduate Record ExaminationsThis practice book containsone actual full-length GRE Physics Test test-taking strategiesBecome familiar withtest structur
UVA - ASTR - 130
%!PS-Adobe-2.0 %Creator: dvipsk 5.58f Copyright 1986, 1994 Radical Eye Software %Title: prepqz-1-f00.dvi %Pages: 4 %PageOrder: Ascend %BoundingBox: 0 0 612 792 %DocumentFonts: Times-Roman Times-Bold Times-Italic %DocumentPaperSizes: Letter %EndCommen
UVA - ASTR - 130
%!PS-Adobe-2.0 %Creator: dvipsk 5.58f Copyright 1986, 1994 Radical Eye Software %Title: prepqz-2-f00.dvi %Pages: 2 %PageOrder: Ascend %BoundingBox: 0 0 612 792 %DocumentFonts: Times-Roman Times-Bold %DocumentPaperSizes: Letter %EndComments %DVIPSComm
Kentucky - JAT - 520
REPRESENTING THE THIRD WAVE: MAINSTREAM PRINT MEDIA FRAMING OF A NEW FEMINIST MOVEMENTBy Carolyn BronsteinThis study analyzes the framing 0 /third wave feminism to determine whether journalists are recycling stock frames commonly used to portray th
Kentucky - JAT - 520
Human Communication. A Publication of the Pacific and Asian Communication Association Vol. 10, No. 1, pp. 33 44The Impact of Television Viewing on Young Adults Stereotypes Towards Hispanic Americans Qingwen Dong and Arthur Phillip MurrilloQingwe
Kentucky - JAT - 520
Copyright 2000. All Rights Reserved.Copyright 2000. All Rights Reserved.Copyright 2000. All Rights Reserved.Copyright 2000. All Rights Reserved.Copyright 2000. All Rights Reserved.Copyright 2000. All Rights Reserved.Copyright 2000. All Ri
Kentucky - JAT - 520
Copyright 2001. All Rights Reserved.Copyright 2001. All Rights Reserved.Copyright 2001. All Rights Reserved.Copyright 2001. All Rights Reserved.Copyright 2001. All Rights Reserved.Copyright 2001. All Rights Reserved.Copyright 2001. All Ri
Kentucky - JAT - 520
Consumer Socialization of Children: A Retrospective Look at Twenty-Five Years of Research Deborah Roedder John The Journal of Consumer Research, Vol. 26, No. 3. (Dec., 1999), pp. 183-213.Stable URL: http:/links.jstor.org/sici?sici=0093-5301%28199912
Kentucky - JAT - 520
Douglas Kellner9/11, SPECTACLES OF TERROR, AND MEDIA MANIPULATION A critique of Jihadist and Bush media politicsThe September 11 attacks on the US dramatized the relationship between media spectacles of terror and the strategy of Islamic Jihadism
Kentucky - JAT - 520
Journat of Pubtic Affairs J Pubt. Aff. 6: 131-146 (2006) Published online in Wiley InterScience (www.interscience.wiley.com) DOI: ]O.10O2/pa.222WILEYInterScience*Public affairs as reality construction: an established paradigm with new implicati
Kentucky - JAT - 520
Journal of Broadcasting &amp; Electronic Media/March 2006Predicting Satellite Radio Adoption via Listening Motives, Activity, and Format PreferenceCarolyn A. LinAs a subscription medium, satellite radio diffusion remains stagnant. To compete effectiv
Kentucky - JAT - 520
Iournal of Broadcasting &amp; Electronic Mcdia/Svptemhei 2004Webcasting Adoption: Technology Fluidity^ User Innovativeness, and Media SubstitutionCarolyn A. LinEven though a tremendous adoption growthtriggered by the increased broadband connections t
Kentucky - JAT - 520
POST-FEMINISM AND POPULAR CULTUREAngela McRobbieIntroduction: Complexification of Backlash?This article presents a series of possible conceptual frames for engaging with what has come to be known as post-feminism. It understands post-feminism to
Kentucky - JAT - 520
Naomi Klein NO LOGOthe first scan &amp; spell-check by fnark, (forgive me Naomi). Note: this text is stripped of notes, photos, graphs, appendix and the index. It is recommended that you buy the paper- or hardback, if you can afford it.Preface Born i
Kentucky - JAT - 520
NAUGHTY GIRLS AND RED BLOODED WOMEN Representations of female heterosexuality in music videoDiane Railton and Paul WatsonIntroductionThere is a moment during the video for Christina Aguileras Cant Hold Us Down in which she appears alongside rappe
Kentucky - JAT - 520
REREthe C REREAD AD Sex andExposing the Hegemonic Feminist Narrative Exposing the Hegemonic Feminist NarrativeAbstract: Sex and the City portrays the lives of four privileged white women and their resistance to challenging their own bigotry in favo