C++ Functions A bit of review (things we’ve covered so far)

Slides:



Advertisements
Similar presentations
CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
Advertisements

Chapter 7: User-Defined Functions II
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
Chapter 5 Functions.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 10: Appendices.
CS Winter 2011 Introduction to the C programming language.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.
1. 2 FUNCTION INLINE FUNCTION DIFFERENCE BETWEEN FUNCTION AND INLINE FUNCTION CONCLUSION 3.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
CSE 332: C++ functions Review: What = and & Mean In C++ the = symbol means either initialization or assignment –If it’s used with a type declaration, it.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
Variables, Functions & Parameter Passing CSci 588 Fall 2013 All material not from online sources copyright © Travis Desell, 2011.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
CSE 332: C++ debugging in Eclipse C++ Debugging in Eclipse We’ve now covered several key program features –Variable declarations, expressions and statements.
CSE 232: C++ pointers, arrays, and references Overview of References and Pointers Often need to refer to another object –Without making a copy of the object.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 5 An Array Class Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
Parameter Passing Mechanisms Reference Parameters Read § §
CSE 332: C++ execution control statements Overview of C++ Execution Control Expressions vs. statements Arithmetic operators and expressions * / % + - Relational.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
Parameter Passing Mechanisms Reference Parameters § §
CSE 232: C++ debugging in Visual Studio and emacs C++ Debugging (in Visual Studio and emacs) We’ve looked at programs from a text-based mode –Shell commands.
CSE 332: C++ debugging Why Debug a Program? When your program crashes –Finding out where it crashed –Examining program memory at that point When a bug.
Slide 1 Chapter 8 Operator Overloading, Friends, and References.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Computing and Statistical Data Analysis Lecture 6 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Introduction to classes and objects:
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
More About Data Types & Functions. General Program Structure #include statements for I/O, etc. #include's for class headers – function prototype statements.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Using Member Functions and Data Members.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
CSE 332: C++ debugging in Eclipse C++ Debugging in Eclipse We’ve looked at programs from a text-based mode –Shell commands and command lines –Text editors,
CSIS 123A Lecture 7 Static variables, destructors, & namespaces.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
CSE 332: C++ expressions Expressions: Operators and Operands Operators obey arity, associativity, and precedence int result = 2 * 3 + 5; // assigns 11.
Lecture 01d: C++ review Topics: functions scope / lifetime preprocessor directives header files C structures ("simple classes")
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
CSE 332: Scientific debugging in C++ Scientific Debugging in C++ (with Eclipse & gdb) By now we’ve covered several key C++ features –Variable declarations.
Pointer to an Object Can define a pointer to an object:
Chapter 7: User-Defined Functions II
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Motivation and Overview
Suppose we want to print out the word MISSISSIPPI in big letters.
FUNCTIONS In C++.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Student Book An Introduction
C Basics.
Programmazione I a.a. 2017/2018.
Introduction to Classes
Built-In (a.k.a. Native) Types in C++
When your program crashes
Presentation transcript:

C++ Functions A bit of review (things we’ve covered so far) We’ll distinguish functions vs. member functions main is a member of a class in Java, but not in C++ Declarations (prototypes without a body) belong in header files Definitions belong in source files (compilation units) Today we’ll cover Function declarations, definitions, and calls Parameter and variable declarations, const and & Function arguments passed by reference vs. by value Inlining functions, and default function arguments Libraries often offer lots of helpful functions E.g., strlen () from the <cstring> library (text, pp. 116) E.g., strcmp () from the <cstring> library (text, pp. 201) E.g., isalpha () from the <cctype> library (text, pp. 249)

Declaring, Defining, and Calling C++ Functions // function declarations in myfile.h void foo (); void baz (int j); // function definitions in myfile.cc void foo (){ int i = 7; // foo calls baz, passing variable i to it baz (i); } void baz (int j){ cout << j << endl; // prints passed value

Parameter/Variable Declarations Read function parameter & variable declarations right to left int i; “i is an integer” int & r = i; “r is a reference to an integer (initialized with i)” int * p; “p is a pointer to an integer” int * & q = p; “q is a reference to a pointer to an integer (initialized with p)” “function main takes an integer and an array of pointers to char, and returns an integer” int main (int argc, char * argv[]); “function usage takes a pointer to char, and returns void” void usage (char * program_name); “function getstring takes a reference to a (C++) string, and returns void” void getstring (string & s);

How Const Works Making something const says that a value cannot be changed through it It’s ok for a const reference or pointer to access a non-const variable/object Not ok for a non-const pointer or reference to access a const variable/object const int i = 7; // value of i cannot be changed int j = 7; // value of j can be changed const int & r = i; // r cannot be used to change i const int & s = j; // s cannot be used to change j // cannot say int & t = i; int * p = 0; “p is a pointer to an integer” const int * q = 0; “q is a pointer to an integer that’s const” int const * r = 0; “r is a pointer to a const integer (same as q, less common)” int * const s = 0; “s is a const pointer to an integer (similar to an array)” const int * const t = 0; “t is a const pointer to an integer that’s const” const int & u = i; “u is a reference to an integer that’s const” const int * & v = q; “v is a reference to a pointer to an integer that’s const” int * const & w = s; “w is a reference to a const pointer to an integer” const int * const & x = t; “x is a reference to a const pointer to an integer that’s const”

What & Means Remember how = can mean either initialization or assignment? If it’s used with a type declaration, it means initialization If it’s used without a type declaration, it means assignment int j = 7; // j is initialized with value 7 j = 3; // j is assigned value 3 In C++, the & symbol also has a similar “dual nature” If it’s used inside a type declaration, it means a reference (an alias) If it’s used outside a type declaration, it means “address of” int & s = j; // reference s initialized to refer to j int * p = & j; // pointer p initialized w/ j’s address

Pass By Value void foo () { int i = 7; baz (i); } void baz (int j) local variable i Think of this as declaration with initialization, along the lines of: int j = what baz was passed; argument variable j (initialized with the value passed to baz, then assigned value 3) 7 → 3

Pass By Reference void foo () { int i = 7; baz (i); } again declaration with initialization int & j = what baz was passed; void foo () { int i = 7; baz (i); } void baz (int & j) j = 3; 7 → 3 local variable i j is initialized to refer to the variable that was passed to baz: when j is assigned 3, the passed variable is assigned 3. 7 → 3 argument variable j

More About Functions in C++ Inlining Makes use of simple functions faster (at a cost) Default Arguments Fill in information the caller does not specify Can live without these features in many cases Due to compiler versions Due to other design considerations However, they can be useful in some cases Workarounds may add code/design complexity Or may result in some performance degradation

How Function Calls Work A function call uses the “program call stack” Stack frame “pushed” when the call is made Execution jumps to the function’s code block Function’s code block is executed Execution returns to just after where call was made Stack frame is “popped” This incurs a (small) performance cost Copying arguments, other info into the stack frame Stack frame management Copying function result back out of the stack frame

Motivation for Inlining If the function body is small Computer might do more work manipulating the stack frame than in the actual function Classic computer science tradeoff If we spend some more space, can we save time? We can ask the compiler to use function inlining Intention: a directive, sometimes just a request

How Inlining Works Basic idea Instead of pushing a stack frame, … … do all of the work in place Compiler makes an “in line” copy of the code at each place where it’s called Code is inserted once for every function call made Rather than the code being in a single place, as for standard function calls

Benefits and Costs of Inlining Especially good for small repetitive function calls Class/struct member accessors and mutators Empty or very simple implementations Be aware of how much inlining will cost How often are the calls invoked? Use code analysis tools What is the relative cost of the function call Compared to code being inlined Shorter functions have higher relative call costs Space cost can be non-trivial Especially if space is limited (embedded systems)

Limitations for Inlining There are limitations on when inlining can be used Depend on the compiler and target The inline keyword is just a suggestion to the compiler Increase portability: make inlining requests optional Same code can be used with inlining on or off Clever use of #define pre-compiler directive, and an additional kind of file: inline (.inl) file See example, next

Example of Portable Inlining // foo.h #ifdef USE_INLINE #define INLINE inline #include “foo.inl” #else #define INLINE double square(const double x); #endif // foo.cpp #include “foo.h” #ifndef USE_INLINE // foo.inl INLINE double square(const double x) {return x * x;} Header file (foo.h) Macro to control inlining Includes implementation if inlining is on Source file (foo.cpp) Includes implementation if inlining is off Inline file (foo.inl) Actual function definition

Building with Portable Inlining Control inlining on the compile line g++ -DUSE_INLINE –o foo foo.cpp Or in the Makefile CXXFLAGS = -DUSE_INLINE This adds a bit of complexity to your code base, … … but can make it more portable across platform architectures and C++ compilers

Default Arguments Some functions can take several arguments Can increase function flexibility Can reduce proliferation of near-identical functions But, callers must supply all of these arguments Even for ones that aren’t “important” We can provide defaults for some arguments Caller doesn’t have to fill these in

Required vs. Default Arguments Function with required argument // call as foo(2); (prints 2) void foo(int a); void foo(int a) {cout << a << endl;} Function with default argument Notice only the declaration gives the default value // can call as foo(2); (prints 2) // or can call as foo(); (prints 3) void foo(int a = 3);

Defaults with Multiple Arguments Function with one of two arguments defaulted // can call as foo(2); (prints 2 3) // or can call as foo(2, 4); (prints 2 4) void foo(int a, int b = 3); void foo(int a, int b) {cout << a << “ ” << b << endl;} Same function, with both arguments defaulted // can call as foo(); (prints 1 3) // or can call as foo(2); (prints 2 3) void foo(int a = 1, int b = 3);

Default Argument Limitations Watch out for ambiguous signatures foo(); and foo(int a = 2); for example Can only default the rightmost arguments Can’t declare void foo(int a = 1, int b); Caller must supply leftmost arguments Even if they’re the same as the defaults

For Next Time Topic: C++ Debugging in Eclipse Assigned readings: none Please make sure to catch up if needed