Chapter 6 CS 3370 – C++ Functions.

Slides:



Advertisements
Similar presentations
11-Jun-14 The assert statement. 2 About the assert statement The purpose of the assert statement is to give you a way to catch program errors early The.
Advertisements

Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Overview scope - determines when an identifier can be referenced in a program storage class - determines the period of time during which that identifier.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
Review of C++ Programming Part II Sheng-Fang Huang.
Computer Science 340 Software Design & Testing Design By Contract.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
High-Level Programming Languages: C++
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
chap13 Chapter 13 Programming in the Large.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
CS 261 – Data Structures Preconditions, Postconditions & Assert.
Introduction to Exception Handling and Defensive Programming.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
18. DECLARATIONS.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
SWE 4743 Abstract Data Types Richard Gesick. SWE Abstract Data Types Object-oriented design is based on the theory of abstract data types Domain.
Defensive Programming CNS 3370 Copyright 2003, Fresh Sources, Inc.
1 Chapter 9 Scope, Lifetime, and More on Functions.
1 Scope Lifetime Functions (the Sequel) Chapter 8.
CSIS 123A Lecture 7 Static variables, destructors, & namespaces.
Design by Contract. The Goal Ensure the correctness of our software (correctness) Recover when it is not correct anyway (robustness) Correctness: Assertions.
Functions CMSC 202. Topics Covered Function review More on variable scope Call-by-reference parameters Call-by-value parameters Function overloading Default.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
Chapter 6 Modularity Using Functions
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Unit 10 Code Reuse. Key Concepts Abstraction Header files Implementation files Storage classes Exit function Conditional compilation Command-line arguments.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 17 – Specifications, error checking & assert.
C++ Lesson 1.
Class Invariants Class invariants are logical conditions to ensure the correct working of a class. Class invariants must hold true when an object is created,
Overview 4 major memory segments Key differences from Java stack
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Logger, Assert and Invariants
Introduction to C++ Systems Programming.
CSE 374 Programming Concepts & Tools
Testing and Debugging.
Why exception handling in C++?
CSE 143 Error Handling [Section 2.8] 3/30/98 CSE 143.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Programmazione I a.a. 2017/2018.
Chapter 14: Exception Handling
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Chapter 9 Scope, Lifetime, and More on Functions
Chapter 4: Control Structures I (Selection)
Overview 4 major memory segments Key differences from Java stack
FUNCTIONS& FUNCTIONS OVERLOADING
Additional Control Structures
CSC 143 Error Handling Kinds of errors: invalid input vs programming bugs How to handle: Bugs: use assert to trap during testing Bad data: should never.
Lab 1 Introduction to C++.
Chapter 6: Repetition Statements
NASA Secure Coding Rules
Repetition Statements (Loops) - 2
CS 144 Advanced C++ Programming January 31 Class Meeting
Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.
Computer Science 340 Software Design & Testing
Functions Reasons Concepts Passing arguments to a function
The Three Attributes of an Identifier
CMSC 202 Lesson 5 Functions I.
Presentation transcript:

Chapter 6 CS 3370 – C++ Functions

Static vs. Automatic Data Function parameters and local variables have function scope: they are visible only inside the function body But lifetime is a separate matter dependent on storage class Storage Class: automatic Live and die with the function static Alive for the entire program dynamic Live on heap; programmer controlled

A Counter Function int counter() { static int count = 0; return ++count; } int main() { for (int i = 0; i < 5; ++i) cout << counter() << ' '; // 1 2 3 4 5 cout << endl;

Command-line Arguments Arguments to main Passed as a pair: int main(int argc, char* argv[]) {…} The first argument is the name of the executable Can’t use range-based for to traverse why?

Getting Command-line Arguments Charless-MacBook-Pro:3370 chuck$ c++ -o args args.cpp Charless-MacBook-Pro:3370 chuck$ ./args one 2 three ./args one 2 three Charless-MacBook-Pro:3370 chuck$ cat args.cpp #include <iostream> using namespace std; int main(int argc, char* argv[]) { for (int i = 0; i < argc; ++i) cout << argv[i] << ' '; cout << endl; }

Variable-length Argument Lists If all are of same type: use Initializer Lists If different types: use variadic templates Both new in C++11 Containers have constructors that take initializer lists.

void args(initializer_list<int> stuff) { for (auto arg: stuff) cout << arg << ' '; cout << endl; } void args2(vector<int> stuff) { void args3(list<int> stuff) { int main() { args({1,2,3}); args2({4,5,6,7}); args3({8,9,10});

Inline Functions Small, simple functions can be “inlined” the compiler inserts raw code avoiding function call-and-return overhead use inline keyword before function definition Useful when calling functions from intensive loops Is only a hint to the compiler

constexpr Functions Enforces that any contained computations and return value are compile-time constant constexpr is transitive

<<CAUTION>> Put inline and constexpr definitions in header files The compiler must have access to the code at all times so it can generate appropriate low-level code. There is no danger of multiple definitions due to multiple includes inline and constexpr item have no “external linkage” they are values inserted inline in generated code

Assertions The assert( ) macro defined in <cassert> It aborts the program if its argument is zero or false can be turned off Used for debugging not handling user errors! use exceptions for those Used to enforce program invariants conditions that should be true by design

CS 3370 - Defensive Programming Assertions in C++ The assert( ) macro: prints the failed expression, file, and line number Enabled by default Can turn off with NDEBUG: #define NDEBUG // must appear before the include! #include <cassert> Or use a compiler option (-NDEBUG) this is “release mode” NDEBUG == release mode

<<WARNING!>> CS 3370 - Defensive Programming <<WARNING!>> Never put needed executable code germane to the program in an assert! It disappears when assertions are disabled

Invariants The Most Important Technique You’re Not Using! CS 3370 - Defensive Programming Invariants The Most Important Technique You’re Not Using! Conditions that do not “vary” “Design mileposts” in your code Loop invariants Class invariants Method invariants Plain old invariants

CS 3370 - Defensive Programming Loop Invariants A condition that is true at the beginning of each loop iteration and when the loop terminates Help ensure program correctness Invariant + termination condition => goal Often conceptual Sometimes can’t test; must be commented instead Example: sortInvariant.cpp, C02/HiLo.cpp

CS 3370 - Defensive Programming Class Invariants All constructors should place their object in a valid state All methods should leave their object in a valid state What constitutes valid object state is called a class invariant Example: Rational class (1410 program) gcd(num,den) == 1

Enforcing Class Invariants CS 3370 - Defensive Programming Enforcing Class Invariants Place appropriate assertions at: the end of each constructor the beginning and end of each non-private method (at least) (private methods may only do part of a computation and therefore the invariant may not be restored until all private methods called by a public method finish)

Method Invariants aka Preconditions and Postconditions CS 3370 - Defensive Programming Method Invariants aka Preconditions and Postconditions Concern the rights and obligations of the method and the caller The “right” of one is the “obligation” of the other The method expects certain preconditions “the input must be non-zero” “the file exists” The caller expects certain postconditions “the answer will be positive” “the file will be closed”

Enforcing Method Invariants CS 3370 - Defensive Programming Enforcing Method Invariants Choices: 1) Ignore 2) Use assertions 3) Throw exceptions 1) is never really an option :-)

CS 3370 - Defensive Programming Using Assertions Assertions are used for conditions that do not directly involve the client of your code Conditions you set/observe internally Loop invariants, class invariants, etc. Often used with private and protected methods For their pre- and post-conditions A debugging aid You don’t “recover” from assertions Program correctness == no assertion failures Protected methods are a gray area; you can choose whether to use assertions or exceptions. Depends on whether base class developers consider derived clients to be “external” or not. I don’t; I prefer assertions.

Static Assertions C++11 only CS 3370 - Defensive Programming Static Assertions C++11 only Constant integral expressions can be checked at compile time static_assert(<expression>, <message>); See static_assert.cpp

Pointers to Functions Most useful when passing functions as arguments Functions cannot be passed by value (duh) When you pass a function as an argument, a “pointer” is passed You don’t always have to use pointer syntax but you can (makes you a C hacker :-) See funptr.cpp