Lecture 01d: C++ review Topics: functions scope / lifetime preprocessor directives header files C structures ("simple classes")

Slides:



Advertisements
Similar presentations
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.
Advertisements

Pointers Typedef Pointer Arithmetic Pointers and Arrays.
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 5 Functions.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
More on Functions Programming. COMP104 Lecture 19 / Slide 2 Passing Parameters by Reference l To have a function with multiple outputs, we have to use.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
File Review Declare the File Stream Object Name –ofstream for output to file –ifstream for input from file Associate a File Name with the File Stream Object.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Chapter 6: Functions.
1 Further C  Multiple source code file projects  Structs  The preprocessor  Pointers.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
February 11, 2005 More Pointers Dynamic Memory Allocation.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
ACM C++ Tutorial Nathan Ratliff. Development Environments Windows – Microsoft Visual C++ Note: It’s not ansi standard Linux / Unix – GCC / G++
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.
Functions CIS Feb-06. Summary Slide Using Functions Mathematical Functions Misc. Functions Naming Conventions Writing Functions –Function Prototype.
 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures.
Dynamic memory allocation and Pointers Lecture 4.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Lecture 3: Getting Started & Input / Output (I/O) “TRON” Copyright 1982 (Walt Disney Productions)
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Week 2. Functions: int max3(int num1, int num2, int num3) {int result; result = max(max(num1,num2),num3); return result; } //max3.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
CS 261 – Data Structures Introduction to C Programming.
#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.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
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?
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Lecture 01c: C++ review Topics: static arrays array / pointer connection dynamic arrays (and pointers) 2D arrays.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
CSE 1341 Honors Note Set 2 1. Overview  Java vs. C++  Functions in C++  First Programming Packet  Development Environment 2.
Arrays  an array of 5 ints is filled with 3,2,4,1,7 int a[5] = {3,2,4,1,7}; // note squiggly brackets  an array of 3 floats is filled with 3.2,1.4,0;
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.
Lecture 01a: C++ review Topics: Setting up projects, main program Memory Diagrams Variables / Types (some of) the many-types-of-const's Input / Output.
Department of Electronic & Electrical Engineering Functions Parameters Arguments Pointers/dereference & * Scope Global/Local Storage Static/Automatic.
Struct s (7.4) Used as data aggregates for an entity can be different types of data e.g. for student id, name, GPA, address,... Similar to classes, but.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 7 – Pointers.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
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.
C++ Functions A bit of review (things we’ve covered so far)
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.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
LECTURE 3 PASS BY REFERENCE. METHODS OF PASSING There are 3 primary methods of passing arguments to functions:  pass by value,  pass by reference, 
Lecture 3: Getting Started & Input / Output (I/O)
Overview 4 major memory segments Key differences from Java stack
C Basics.
User-defined Functions
Overview 4 major memory segments Key differences from Java stack
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
User-defined Functions
Given the code to the left:
C++ Compilation Model C++ is a compiled language
Arrays an array of 5 ints is filled with 3,2,4,1,7
Function Defaults C++ permits functions to be declared with default values for some, or all, of its parameters Allows for the function to be called without.
What Is? function predefined, programmer-defined
CS1201: Programming Language 2
Class rational part2.
Presentation transcript:

Lecture 01d: C++ review Topics: functions scope / lifetime preprocessor directives header files C structures ("simple classes")

Part I: functions Basic syntax – Declaration (if a function call comes before the definition) return-value func_name([parameters]); – Body return-value func_name(parameters) body The return type can be void if the function isn't meant to return anything.

Example void printAmt(float amt);// prototype float calculateTax(float base, float rate=0.07f) { float total; total = base * (1.0f + rate); return total; } int main() { float price, rate; cout << "Enter price: "; cin >> price; cout << "Tax rate (0.0 for default): "; cin >> rate; if (rate == 0.0) printAmt(calculateTax(price)); else printAmt(calculateTax(price, rate)); } void printAmt(float amt) { cout.setf(ios::fixed); cout.precision(2); cout << "$" << amt << endl; } [Show / Discuss Call Stack] [Talk about scope / lifetime]

Pointer parameters Useful because: – Passing a pointer is often much cheaper than copying a large argument (e.g. objects) – Allows us to modify what the pointer points to. Especially useful if we want to "return" more than 1 value. void foo(ReallyBigDataStructure * d)// only copies 4 bytes! {} void fooBad(ReallyBigDataStructure s) // copies mucho bytes { } int getImageSize(SDL_Surface * s, int * w, int * h) {// s is input; w and h are "return" values int error = 0; if (s == NULL)error = 1; else { *w = s->w; *h = s->h; } return error; }

Another interpretation of pointer parameters Syntactically the same as last slide. But since a pointer = address, it could be pointing to an array – Documentation is important! // p is a pointer to an array of 3 values. This // function returns the sum of those 3 values. int func(int * p) { return p[0] + p[1] + p[2]; } int main() { int values[3] = {5, 7, 13}, result; result = func(values); } #include using namespace std; // p is a pointer to a single integer. This func // sets that value to the current hour and returns // the current minutes. int func(int * p) { time_t t = time(0); struct tm * now = localtime(&t); *p = now->tm_hour; return now->tm_min; } int main() { int hour, minutes; minutes = func(&hour); }

Reference Parameters C++ only Really does pass-by-pointer, but hides it int getImageSize(SDL_Surface * s, int & w, int & h) { int error = 0; if (s == NULL) error = 1; else { w = s->w;// Note: de-reference is done... h = s->h;//...automatically } return error; }

Part II: Scope Levels Global scope – Defined outside all blocks – Accessible anywhere (might need extern) File scope – Like global, but with static qualifier – Only accessible in this file. Local scope (parameters, local variables) Block scope – "closest" blocks are used first

Example int x = 15; // global scope static float y = 1.2;// file scope int func(int a, float b) // a & b have local scope { double c = a * 2 + b / x;// c too... if (c < 10.0) { int y;// block scope //... } return (int)c; } int main() { int x;// Local scope – masks global x x = func(x, y); }

static modifier Two uses (a third in classes) – To indicate file scope – To make a "persistent" variable in a function static int x; // file scope void func() { static int counter = 0; // A "persistent" variable. Only initialized once counter++; }

Part III: Pre-processor directives Entirely textual (not C/C++ code)! Are completely evaluated before the compiler starts. All start with a pound (#)

Example #if _WIN32 #include #endif #include "my_file.h" #define REAL float #define VERBOSE void doSomething() { #ifdef VERBOSE cout << "Starting 'doSomething'..."; #endif // *really* do something #if VERBOSE cout << "done! time="; #ifdef _DEBUG cout << calculateTime() << endl; #else cout << endl; #endif }

Macro's cont. Some lesser-used directives #undef Macro functions #define MIN(a, b) a < b ? a : b #define SFUNC(msg, funcName, eCode) cout << msg << "…" \ if (funcName() != 0) return eCode; \ cout << "done!\n"; Built-in macros (compiler dependent) __LINE__ __FILE__ _DEBUG _WIN32 _GCC __VERSION__

Part IV: Header files The compiler compiles all source files into object files The linker combines all object files (and other libraries) into the executable. Header files are useful to store "common" information which is (possibly) used in multiple places – function prototypes – other include files (iostream, …) – macros – [later] class declarations

Example #ifndef _MY_HEADER_H_// Not always necessary, but #define _MY_HEADER_H_// can prevent a 'multiple // declarations of "x" error.' #include using namespace std; void myFunc(int a, float b); // Other things... #endif

Part V: C-style structures Basically, a collection of data – Similarities to arrays: single name, multiple values – Differences from arrays: access individual values by name (structs) instead of by position (arrays) Can have different types of data (heterogeneous); array elements must be the same (homogeneous) Two parts: – defining the structure (a new type) – Creating variables of that type.

Example of structs // Part I: Define a type (could go in a.h file...) struct employeeData { string name; int id; float salary; };// <== don't forget the semi-colon! int main() { employeeData record;// Part II: Make variables employeeData record2;//...another one record.id = 15; record.name = "Joe Smith"; record.salary = f; record2.id = 16;// Doesn't change record's data cout << "record.id = " << record.id << endl; }

Pointers to structures // employeeData struct defined as before void outputEData(employeeData * e) { //cout << (*e).name << endl;// ugly... cout name << endl;// much nicer! for (int i=0; i name.size(); i++) cout << "="; cout << "\n\tid = " << (*e).id << endl; cout salary << endl; } int main() { employeeData curRec; // curRec is filled in... outputEData(&curRec); }

Dynamic allocation of struct variables // employeeData structure is defined as before. int main() { employeeData * eptr = NULL; eptr = new employeeData; // allocates on heap eptr->name = "Jason"; eptr->id = 99; eptr->salary = f; delete eptr;// Note: no brackets eptr = NULL;// Not required, but prevents // a dangling pointer. }

Pass by pointer, pass-by-value, and pass-by-reference The outputEData function uses pass- by-pointer We could also re- write it using pass- by-value [Advantages / Disadvantages of each] [Show stack for each] // pass-by-pointer void funcPBP(employeeData * e) {e->salary += 1.0f; } // pass-by-value void funcPBV(employeeData e) { e.salary += 1.0f; } // pass-by-reference void funcPBR(employeeData & e) { e.salary += 1.0f; } int main() { employeeData r1 = {“Joe”, 1, 200.0f}; employeeData r2 = {“Sue”, 2, 300.0f}; employeeData r3 = {“Bob”, 3, 400.0f}; funcPBP(&r1); funcPBV(r2); funcPBR(r3); cout << r1.salary << “\n”; // cout << r2.salary << “\n”; // cout << r3.salary << “\n”; // }