Chapter 8 Technicalities: Functions, etc. John Keyser’s Modifications of Slides by Bjarne Stroustrup www.stroustrup.com/Programming.

Slides:



Advertisements
Similar presentations
Chapter 8 Technicalities: Functions, etc. Bjarne Stroustrup
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 5: Functions 1 Based on slides created by Bjarne Stroustrup.
Chapter 5 Functions.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
Computer Science 1620 Functions. Given a number n, the factorial of n, written n!, is computed as follows: note: 0! = 1 examples: n! = n x (n-1) x (n-2)
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12A Separate Compilation and Namespaces For classes this time.
Your First C++ Program Aug 27, /27/08 CS 150 Introduction to Computer Science I C++  Based on the C programming language  One of today’s most.
Computer Science 1620 Function Scope & Global Variables.
CS 201 Functions Debzani Deb.
Miscellaneous topicsCS-2301 B-term Miscellaneous Topics CS-2301, System Programming for Non-majors (Slides include materials from The C Programming.
1 8/30/06CS150 Introduction to Computer Science 1 Your First C++ Program.
 2007 Pearson Education, Inc. All rights reserved C++ as a Better C; Introducing Object Technology.
Computer Science 1620 Lifetime & Scope. Variable Lifetime a variable's lifetime is finite Variable creation: memory is allocated to the variable occurs.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 6: Functions.
You gotta be cool. C++ ? C++ Standard Library Header Files Inline Functions References and Reference Parameters Default Arguments and Empty Parameter.
Organizing Programs and Data 2 Lecture 7 Hartmut Kaiser
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 3: Requirements Specification, C++ Basics.
Scope Accessibility of Names. Review We’ve seen that C++ permits a programmer to declare names and then use those names in a manner consistent with their.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 6 Writing a Program John Keyser’s Modification of Slides by Bjarne Stroustrup
Variable Scope Storage Class Recursion
1 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing:
C++ Functions. Objectives 1. Be able to implement C++ functions 2. Be able to share data among functions 2.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and.
CPS120: Introduction to Computer Science Functions.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Looping and Counting Lecture 3 Hartmut Kaiser
Chapter 8 Technicalities: Functions, etc. Bjarne Stroustrup
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.
1 CS161 Introduction to Computer Science Topic #9.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
1 8/31/05CS150 Introduction to Computer Science 1 Hello World!
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
Manish K Parmar PGT (CS) K V VVNagar Thursday, December 24, 2015 Lesson on USER DEFINED FUNCTION IN C++ Presented by Manish K Parmar PGT Computer Science.
By Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 13 More on Classes Chapter 8 Week 13 More on Classes Chapter 8.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
L what are predefined functions? l what is? n function name n argument(s) n return value n function call n function invocation n nested function call l.
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
Computing and Statistical Data Analysis Lecture 6 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Introduction to classes and objects:
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
CSC1201: Programming Language 2 1 Functions. 2 Function declaration: return_type FuncName( Type arg1, Type arg2,….. Type argN) { function body } A program.
1 Introduction to Object Oriented Programming Chapter 10.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
1 8/30/06CS150 Introduction to Computer Science 1 Your First C++ Program.
CSCE Introduction to Program Design and Concepts J. Michael Moore Spring 2015 Set 6: Miscellaneous 1 Based on slides created by Bjarne Stroustrup.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 8 Technicalities: Functions, etc. Hartmut Kaiser
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
User-Written Functions
Global & Local Identifiers
#include "std_lib_facilities
Chapter 8 Technicalities: Functions, etc.
Chapter 8 Technicalities: Functions, etc.
Chapter 8 Technicalities: Functions, etc.
Presentation transcript:

Chapter 8 Technicalities: Functions, etc. John Keyser’s Modifications of Slides by Bjarne Stroustrup

Class Info Test: Over chapters 1-9 – Will “Finish” this week – Date possibilities: Feb. 11, 13, 18, 20 Homework problems Grammars and the Calculator – Will come back to grammars today after slides – Would like to return to calculator later

Abstract This lecture and the following present some technical details of the language to give a slightly broader view of C++’s basic facilities and to provide a more systematic view of those facilities. This also acts as a review of many of the notions presented so far, such as types, functions, and initialization, and provides an opportunity to explore our tool without adding new programming techniques or concepts. 3Stroustrup/Programming

Overview Language Technicalities Declarations – Definitions – Headers and the preprocessor – Scope Functions – Declarations and definitions – Arguments Call by value, reference, and const reference Namespaces – “Using” statements 4Stroustrup/Programming

Language technicalities Are a necessary evil – A programming language is a foreign language – When learning a foreign language, you have to look at the grammar and vocabulary – We will do this in this chapter and the next Because: – Programs must be precisely and completely specified A computer is a very stupid (though very fast) machine A computer can’t guess what you “really meant to say” (and shouldn’t try to) – So we must know the rules Some of them (the C++11 standard is 1,310 pages) However, never forget that – What we study is programming – Our output is programs/systems – A programming language is only a tool 5Stroustrup/Programming

Technicalities Don’t spend your time on minor syntax and semantic issues. There is more than one way to say everything – Just like in English Most design and programming concepts are universal, or at least very widely supported by popular programming languages – So what you learn using C++ you can use with many other languages Language technicalities are specific to a given language – But many of the technicalities from C++ presented here have obvious counterparts in C, Java, C#, etc. 6Stroustrup/Programming

Declarations A declaration introduces a name into a scope. A declaration also specifies a type for the named object. Sometimes a declaration includes an initializer. A name must be declared before it can be used in a C++ program. Examples: – int a = 7;// an int variable named ‘a’ is declared – const double cd = 8.7;// a double-precision floating-point constant – double sqrt(double);// a function taking a double argument and // returning a double result – vector v; // a vector variable of Tokens (variable) 7Stroustrup/Programming

Declarations Declarations are frequently introduced into a program through “headers” – A header is a file containing declarations providing an interface to other parts of a program This allows for abstraction – you don’t have to know the details of a function like cout in order to use it. When you add #include "std_lib_facilities_3.h" to your code, the declarations in the file std_lib_facilities_3.h become available (including cout etc.). 8Stroustrup/Programming

Definitions A declaration that (also) fully specifies the entity declared is called a definition – Examples int a = 7; int b;// an (uninitialized) int vector v;// an empty vector of doubles double sqrt(double) { … }; // a function with a body struct Point { int x; int y; }; – Examples of declarations that are not definitions double sqrt(double);// function body missing struct Point; // class members specified elsewhere extern int a;// extern means “not definition” // “extern” is archaic; we will hardly use it 9Stroustrup/Programming

Declarations and definitions You can’t define something twice – A definition says what something is – Examples int a;// definition int a;// error: double definition double sqrt(double d) { … }// definition double sqrt(double d) { … }// error: double definition You can declare something twice – A declaration says how something can be used int a = 7;// definition (also a declaration) extern int a;// declaration double sqrt(double);// declaration double sqrt(double d) { … }// definition (also a declaration) 10Stroustrup/Programming

Why both declarations and definitions? To refer to something, we need (only) its declaration Often we want the definition “elsewhere” – Later in a file – In another file preferably written by someone else Declarations are used to specify interfaces – To your own code – To libraries Libraries are key: we can’t write all ourselves, and wouldn’t want to In larger programs – Place all declarations in header files to ease sharing 11Stroustrup/Programming

Header Files and the Preprocessor A header is a file that holds declarations of functions, types, constants, and other program components. The construct #include "std_lib_facilities_3.h" is a “preprocessor directive” that adds declarations to your program – Typically, the header file is simply a text (source code) file A header gives you access to functions, types, etc. that you want to use in your programs. – Usually, you don’t really care about how they are written. – The actual functions, types, etc. are defined in other source code files Often as part of libraries 12Stroustrup/Programming

Source files A header file (here, token.h) defines an interface between user code and implementation code (usually in a library) The same #include declarations in both.cpp files (definitions and uses) ease consistency checking 13 // declarations: class Token { … }; class Token_stream { Token get(); … }; … #include "token.h" //definitions: Token Token_stream::get() { /* … */ } … #include "token.h" … Token t = ts.get(); … token.h: token.cpp: use.cpp: Stroustrup/Programming

Scope A scope is a region of program text – Examples Global scope (outside any language construct) Class scope (within a class) Local scope (between { … } braces) Statement scope (e.g. in a for-statement) A name in a scope can be seen from within its scope and within scopes nested within that scope After the declaration of the name (“can't look ahead” rule) A scope keeps “things” local Prevents my variables, functions, etc., from interfering with yours Remember: real programs have many thousands of entities Locality is good! – Keep names as local as possible 14Stroustrup/Programming

Scope #include "std_lib_facilities_3.h"// get max and abs from here // no r, i, or v here class My_vector { vector v;// v is in class scope public: int largest()// largest is in class scope { int r = 0; // r is local for (int i = 0; i<v.size(); ++i) // i is in statement scope r = max(r,abs(v[i])); // no i here return r; } // no r here }; // no v here 15Stroustrup/Programming

Scopes nest int x;// global variable – avoid those where you can int y;// another global variable int f() { int x;// local variable (Note – now there are two x’s) x = 7;// local x, not the global x { int x = y;// another local x, initialized by the global y // (Now there are three x’s) x++;// increment the local x in this scope } // avoid such complicated nesting and hiding: keep it simple! 16Stroustrup/Programming

Functions General form: – return_type name (formal arguments); // a declaration – return_type name (formal arguments) body// a definition – For example double f(int a, double d) { return a*d; } Formal arguments are often called parameters If you don’t want to return a value give void as the return type void increase_power(int level); – Here, void means “don’t return a value” A body is a block or a try block – For example { /* code */ }// a block try { /* code */ } catch(exception& e) { /* code */ }// a try block Functions represent/implement computations/calculations 17Stroustrup/Programming

Functions: Call by Value // call-by-value (send the function a copy of the argument’s value) int f(int a) { a = a+1; return a; } int main() { int xx = 0; cout << f(xx) << endl;// writes 1 cout << xx << endl; // writes 0; f() doesn’t change xx int yy = 7; cout << f(yy) << endl; // writes 8; f() doesn’t change yy cout << yy << endl; // writes 7 } 18 0 a: xx: copy the value 0 7 a: yy: copy the value 7 Stroustrup/Programming

Functions: Call by Reference // call-by-reference (pass a reference to the argument) int f(int& a) { a = a+1; return a; } int main() { int xx = 0; cout << f(xx) << endl;// writes 1 // f() changed the value of xx cout << xx << endl; // writes 1 int yy = 7; cout << f(yy) << endl; // writes 8 // f() changes the value of yy cout << yy << endl; // writes 8 } xx: yy: a: 1 st call (refer to xx) 2 nd call (refer to yy) Stroustrup/Programming

Functions Avoid (non-const) reference arguments when you can – They can lead to obscure bugs when you forget which arguments can be changed int incr1(int a) { return a+1; } void incr2(int& a) { ++a; } int x = 7; x = incr1(x);// pretty obvious incr2(x);// pretty obscure So why have reference arguments? – Occasionally, they are essential E.g., for changing several values For manipulating containers (e.g., vector) – const reference arguments are very often useful 20Stroustrup/Programming

Call by value/by reference/ by const-reference void f(int a, int& r, const int& cr) { ++a; ++r; ++cr; } // error: cr is const void g(int a, int& r, const int& cr) { ++a; ++r; int x = cr; ++x; } // ok int main() { int x = 0; int y = 0; int z = 0; g(x,y,z);// x==0; y==1; z==0 g(1,2,3);// error: reference argument r needs a variable to refer to g(1,y,3);// ok: since cr is const we can pass “a temporary” } // const references are very useful for passing large objects 21Stroustrup/Programming

References “reference” is a general concept – Not just for call-by-reference int i = 7; int& r = i; r = 9;// i becomes 9 const int& cr = i; // cr = 7;// error: cr refers to const i = 8; cout << cr << endl;// write out the value of i (that’s 8) You can – think of a reference as an alternative name for an object You can’t – modify an object through a const reference – make a reference refer to another object after initialization 22 7 i: r cr Stroustrup/Programming

Guidance for Passing Variables Use call-by-value for very small objects Use call-by-const-reference for large objects Return a result rather than modify an object through a reference argument Use call-by-reference only when you have to For example class Image { /* objects are potentially huge */ }; void f(Image i); … f(my_image); // oops: this could be s-l-o-o-o-w void f(Image& i); … f(my_image); // no copy, but f() can modify my_image void f(const Image&); … f(my_image); // f() won’t mess with my_image 23Stroustrup/Programming

Namespaces Consider this code from two programmers Jack and Jill class Glob { /*…*/ }; // in Jack’s header file jack.h class Widget { /*…*/ }; // also in jack.h class Blob { /*…*/ }; // in Jill’s header file jill.h class Widget { /*…*/ }; // also in jill.h #include "jack.h";// this is in your code #include "jill.h";// so is this void my_func(Widget p)// oops! –error: multiple definitions of Widget { // … } 24Stroustrup/Programming

Namespaces The compiler will not compile multiple definitions; such clashes can occur from multiple headers. One way to prevent this problem is with namespaces: namespace Jack {// in Jack’s header file class Glob{ /*…*/ }; class Widget{ /*…*/ }; } #include "jack.h";// this is in your code #include "jill.h";// so is this void my_func(Jack::Widget p)// OK, Jack’s Widget class will not {// clash with a different Widget // … } 25Stroustrup/Programming

Namespaces A namespace is a named scope The :: syntax is used to specify which namespace you are using and which (of many possible) objects of the same name you are referring to For example, cout is in namespace std, you could write: std::cout << "Please enter stuff… \n"; 26Stroustrup/Programming

using Declarations and Directives To avoid the tedium of – std::cout << "Please enter stuff… \n"; you could write a “using declaration” – using std::cout;// when I say cout, I mean std::cout” – cout << "Please enter stuff… \n"; // ok: std::cout – cin >> x;// error: cin not in scope or you could write a “using directive” – using namespace std; // “make all names from namespace std available” – cout << "Please enter stuff… \n"; // ok: std::cout – cin >> x;// ok: std::cin More about header files in chapter 12 27Stroustrup/Programming

Next talk More technicalities, mostly related to classes 28Stroustrup/Programming