L8_functions

L8_functions - Functions in C+ Functions For : COP 3330....

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Functions For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Piyush Kumar Functions in C++ | Declarations vs Definitions | Inline Functions | Class Member functions | Overloaded Functions | Pointers to functions | Recursive functions What you should know? | Defining a function // return the greatest common divisor int gcd(int v1, int v2) { while (v2) { int temp = v2; v2 = v1 % v2; v1 = temp; } return v1; } function gcd(a, b) if b = 0 return a else return gcd(b, a mod b) Gcd Example 1071,1029 1029, 42 42, 21 21, 0 Function body is a scope Another scope. temp is a local variable Non-reference parameter. Calling a function? #include <iostream> using std::cout; using std::endl; using std::cin; int main() { // get values from standard input cout << "Enter two values: \n"; int i, j; cin >> i >> j; // call gcd on arguments i and j // and print their greatest common divisor cout << "gcd: " << gcd(i, j) << endl; return 0; } Function return types // missing return type Test(double v1, double v2){ /* … */ } int *foo_bar(void){ /* … */ } void process ( void ) { /* … */ } int manip(int v1, v2) { /* … */ } // error int manip(int v1, int v2) { /* … */ } // ok Parameter Type-Checking gcd(“hello”, “world”); gcd(24312); gcd(42,10,0); gcd(3.14, 6.29); // ok? // Statically typed language
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 Pointer Parameters #include <iostream> #include <vector> using std::vector; using std::endl; using std::cout; void reset(int *ip) { *ip = 0; // changes the value of the object to which ip points ip = 0; // changes only the local value of ip; the argument is unchanged } int main() { int i = 42; int *p = &i; cout << "i: " << *p << '\n'; // prints i: 42 reset(p); // changes *p but not p cout << "i: " << *p << endl; // ok: prints i: 0 return 0; } Const parameters | Fcn(const int i) {}… z Fcn can read but not write to i. Reference Parameters
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/27/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue.

Page1 / 6

L8_functions - Functions in C+ Functions For : COP 3330....

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online