Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6 CS 3370 – C++ Functions.

Similar presentations


Presentation on theme: "Chapter 6 CS 3370 – C++ Functions."— Presentation transcript:

1 Chapter 6 CS 3370 – C++ Functions

2 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

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

4 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?

5 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; }

6 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.

7 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});

8 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

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

10 <<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

11 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

12 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

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

14 Invariants The Most Important Technique You’re Not Using!
CS 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

15 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

16 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

17 Enforcing Class Invariants
CS 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)

18 Method Invariants aka Preconditions and Postconditions
CS 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”

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

20 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.

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

22 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


Download ppt "Chapter 6 CS 3370 – C++ Functions."

Similar presentations


Ads by Google