Chapter 2. Procedural Programming

Similar documents
Short Notes of CS201

CS201 - Introduction to Programming Glossary By

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Operators. The Arrow Operator. The sizeof Operator

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

CS2141 Software Development using C/C++ C++ Basics

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

CE221 Programming in C++ Part 1 Introduction

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

CS3157: Advanced Programming. Outline

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

EMBEDDED SYSTEMS PROGRAMMING Language Basics

Object Reference and Memory Allocation. Questions:

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

Tokens, Expressions and Control Structures

UNIT- 3 Introduction to C++

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Creating a C++ Program

COMP322 - Introduction to C++

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Fast Introduction to Object Oriented Programming and C++

Absolute C++ Walter Savitch

CPSC 427: Object-Oriented Programming

2 ADT Programming User-defined abstract data types

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Introduction to C++ Systems Programming

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Chapter 15 - C++ As A "Better C"

CS201 Latest Solved MCQs

III. Classes (Chap. 3)

6.096 Introduction to C++ January (IAP) 2009

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Attributes, Bindings, and Semantic Functions Declarations, Blocks, Scope, and the Symbol Table Name Resolution and Overloading Allocation, Lifetimes,

Chap 0: Overview. Overview of basic C++ syntax Refresh programming basics C++ Vs. Java differences Coding conventions used. EECS 268 Programming II 1

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

Introducing C++ to Java Programmers

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

C++ Quick Guide. Advertisements

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Lecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.)

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

CS 376b Computer Vision

Pointers, Dynamic Data, and Reference Types

Interview Questions of C++

Lecture 2, September 4

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

C++_ MARKS 40 MIN

Your first C++ program

A Fast Review of C Essentials Part I

Review of the C Programming Language for Principles of Operating Systems

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CS2255 HOMEWORK #1 Fall 2012

CS201- Introduction to Programming Current Quizzes

C11: Garbage Collection and Constructors

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

CHAPTER 4 FUNCTIONS. 4.1 Introduction

AN OVERVIEW OF C++ 1

EL6483: Brief Overview of C Programming Language

Basic Types, Variables, Literals, Constants

CPSC 427: Object-Oriented Programming

C++ Programming: Polymorphism

Introduction to C++ (Extensions to C)

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Review of the C Programming Language

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

C++ basics Getting started with, and Data Types.

In Java we have the keyword null, which is the value of an uninitialized reference type

377 Student Guide to C++

CMPS 221 Sample Final

Pointers and References

Introduction to Programming Using Java (98-388)

CSCI 1061U Programming Workshop 2. C++ Basics

C++ For Science and Engineering Lecture 15

2 nd Week Lecture Notes

Introduction to Programming using C++

Model Viva Questions for Programming in C lab

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

OBJECT ORIENTED PROGRAMMING USING C++

Lecture 5: Methods CS2301

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

A First Program - Greeting.cpp

EEE145 Computer Programming

CS242 COMPUTER PROGRAMMING

Variables. Data Types.

Cpt S 122 Data Structures. Introduction to C++ Part II

Strings and Stream I/O

Programming Languages Third Edition. Chapter 7 Basic Semantics

CSCE 206: Structured Programming in C++

Chapter 2 Basic Elements of C++

C++ Programming: From Problem Analysis to Program Design, Third Edition

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

Function Overloading

The C++ Language. Arizona State University 1

Memory Allocation in C

Transcription:

Chapter 2 Procedural Programming

2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic pointer operations.

2: Main function Java C++ Comments about C++ class C { public static void main(string args[]) {... } int main() {... return 0; } The main function is not included in any class.

2: Comments Comments about C++ /*... */ // C++ does not provide the Java comment /**... */, used to create documentation Remember about programming guidelines!

2: Primitive Data Types Comments about C++ char char is one byte long and does not use Unicode short int long float double The language does not define the size and range of numeric primitive data types, which are implementation dependent. There are no predefined wrapper classes for primitive data types.

2: More Primitive Data Types Java C++ Comments about C++ byte -- similar to unsigned char boolean bool Any non-zero numeric value can be treated as true, a zero value can be treated as false String string To use strings you must include the <string> library string language = "C" + "++"; bool mark = language < "Java"; char first = language[0];

2: typedef and sizeof A synonym for an existing type: typedef bool Boolean; Size of data type (in bytes): int k = 5;... sizeof(int)... sizeof k

2: Variables, Constants and Expressions Java C++ final const -- const int LINES = 25; Comma operator, e.g. e1, e2 for(i = 1, j = 2; i < N && j < M; ++i, ++j)...

2: Type Conversions between bool and int Implicit type conversions or casts are performed when: the value is promoted to a more precise type: double d = 3; // 3 is promoted to 3.0 the value is demoted, resulting in a loss of precision: double d = 3.14159; int i = d; // 3.14159 is demoted

2: Type Conversions (cont.) Better to use explicit cast: i = static_cast<int>(d); Example int i, j;... // initialization of i and j double d = static_cast<double>(i) / j; // avoids int division

2: Type Conversions (cont.) Conversion to remove constness, which allows a const identifier to be modified: const int i = 3; const_cast<int>(i) = 1; // not constant reinterpret_cast used to perform a low-level reinterpretation of the bit pattern to force the type conversion dynamic_cast used for derived classes

2: Control Structures Comments about C++ Conditional and switch statements Loops same break or continue cannot be labeled. A goto statement is available (if and when really needed).

2: Basic I/O Three predefined streams: cout - the standard output stream << (put-to) binary operator is used for output cin - the standard input stream >> (get from) operator is used for input cerr - the standard error stream.

2: Basic I/O (cont.) cout << "Enter value "; int i; cin >> i; // prompt // input integer cout << "The value is:"; cout << i; // output integer cout << "The value is:" << i << endl; // chain

// File ex2.1.cpp // Read integer values until a positive value is entered // If a non-integer value is entered, abort the program Example of I/O // Otherwise, output the integer value #include <iostream> int main() { int i = 0; bool correct = false; cout << "Enter a positive integer value" << endl; } while(cin >> i) { if(i > 0) { test for correct input correct = true; break; } cout << "non-positive value; re-enter" << endl; } if(!correct) cout << "incorrect integer value" << endl; else cout << "You entered " << i << endl;

2: Arrays C++ arrays are borrowed from C: Java C++ Comments about C++ int [] marks = new int[10] int marks[10] - lower bound equal to zero - size must be known at compile time The C++ standard library also provides vectors.

2: Reference Data Types A reference data type (which differs from Java references) is of the form type& It is used for: passing parameters and returning values providing an alias in a variable definition (must be initialized in the definition) int i = 1; int& pi = i; // pi is an alias for i pi++; // now i is 2, pi not changed

2: Reference Data Types (cont.) References must be initialized with expressions that are lvalues. You can declare the reference as constant; for example: const int& cpi = 8; (may be initialized with expressions that are not lvalues). Mostly used with parameters.

2: Functions Terminology: an expression that appears in a function call, such as x in f(x), is called an actual parameter, as opposed to the formal parameter that appears in the function definition. Construct Comments about C++ int foo(pars) { body } C++ allows global functions, that is functions that are defined outside of any class (also called stand-alone functions)

2: Functions (cont.) A function may be defined as inline: inline int sum(int i, int j) { return i + j; } which is a request to the compiler to generate code inline. Each call to the inlined function is replaced at compile time by its body: int i = sum(1, k); // replaced by: int i = 1 + k

2: Declarations and Definitions A function declaration merely provides a function signature and the return type: bool prime(int); // note the semicolon A function definition includes the declaration and the implementation of the function. A function can be called only if it has been declared or defined. Each function declaration must come with the documentation to be used by the client. A different kind of information is needed by the implementor of the function, and so the function definition comes with its own documentation.

2: Pass by Value, Pass by Reference, and Constant Pass by Reference Passing parameters by value means that the formal parameter is assigned the value of the actual parameter, and the actual parameter is not modified: void swap(int x, int y) { int temp = x; x = y; y = temp; } int i = 1; int j = 2; swap(i, j);

2: Pass by Value, Pass by Reference, and Constant Pass by Reference Passing by reference allows the function to modify the actual parameter. The type of the parameter passed by reference is a reference type, with an & following the parameter type: void swap(int& x, int& y) { int temp = x; x = y; y = temp; } int i = 3; int j = 4; swap(i, j); // i and j passed by reference

2: Pass by Value, Pass by Reference, and Constant Pass by Reference Constant pass by reference does not allow the client to inadvertently modify the actual parameter: double product(const double& block, int size); If a function has a non-constant parameter, then it may not be called with a constant actual parameter.

Pass by Value and by Reference If you do not want to modify the value of the actual parameter, then use - pass by value for parameters of primitive data types, - constant pass by reference for parameters of structured data types, such as classes. If you do want to modify the value of the actual parameter, then use pass by reference.

2: Default Values of Parameters A default value of a formal function parameter is useful if this function is frequently called with the same actual parameter. The client can call this function either without the actual parameter for this formal parameter (and so using the default value), or with an actual parameter to override the default value. A function move() that typically moves to position 0 by a step of 1 void move(int from, int to = 0, int by = 1);

2: Default Values of Parameters (cont.) Only trailing parameters may be assigned default values: void move(int from, int to = 0, int by); Overriding values of the actual parameters are assigned from left to right: void move(int from, int to = 0, int by = 1); move(2); // move(2, 0, 1) move(2, 3); // move(2, 3, 1) move(2, 3, 4); // move(2, 3, 4) It is not possible to override the second most trailing default parameter, without overriding the first default parameter.

2: Overloading Functions The name of a function should identify the action performed by this function. Overloading a function means that you can have several functions with the same name in a single scope, provided that these functions have different signatures: double max(double, double); int max(int, int); // overloaded bool max(int, int); // identical signatures

2: Overloading Functions (cont.) Sometimes, overloading can be replaced by using default parameter values: void move(int from, int to); void move(int from, int to, int by); can be replaced by a single function: void move(int from, int to, int by = 0);

2: Functions and Arrays When arrays are used as function parameters, their size has to be passed as another parameter: void maxmin(const double arr[], int size, double& max, double& min) { int i; for(max = min = arr[0], i = 1; i < size; ++i) { if(max < arr[i]) max = arr[i]; if(min > arr[i]) min = arr[i]; } }

2: Functions and Arrays (cont.) double arr[] = {1.3, 1.2, 1.1}; double maxi, mini; maxmin(arr, 3, maxi, mini); Consider a different maxmin1(): const double x[] = {3, 1, 7.8}; void maxmin1(double arr[],int size, double& max, double& min); maxmin1(x, 3, max, min); // error, x is const

2: Functions Returning References A function may return a reference type, and if so, a function call is an lvalue: int a[5]; int& index(int x[], int i) { // gives read/write access // to the i-th element of x return x[i]; } cin >> index(a, 1);

2: Functions Returning Constant References Functions may also be designed to provide read-only access, by returning a constant reference: const int& get(const int x[], int i) { } return x[i]; cout << get(a,2); cin >> get(a,1); // can't change the value

2: Pointers and Dynamic Memory Management Static memory is used to store the values of global variables, as well as function and class static variables. Stack-based memory is implicitly managed by function calls and function returns. Heap-based memory is used to dynamically manage memory as a result of a program s request, such as Java's new call.

2: Pointers and Dynamic Memory Management

2: Pointers and Dynamic Memory Management (cont.) Dynamic memory allocation means that a block of memory requested by a program is removed from the heap, and can be used by this program. Dynamic memory deallocation means that a program returns a block of memory to the heap - the de-allocated memory can be used the next time a memory request occurs.

2: Pointers and Dynamic Memory Management (cont.) Garbage collector decides when inaccessible objects are deallocated. Java objects are always allocated on the heap and never on the run-time stack, and all memory deallocation is done automatically by the garbage collector. Memory leakage occurs when memory that is no longer needed by the program has not been freed and made available for reuse. What's a reference to an object in Java? It is a memory address; specifically, the address of a block of memory allocated for this object on the heap.

2: Pointers and Dynamic Memory Management (cont.) In C++: objects may be allocated both on the stack and in the heap there is no standard garbage collector the programmer is fully responsible for explicitly deallocating memory. This may lead to various programming errors: dangling reference problem - the result of a variable referencing a memory block whose lifetime has expired (allocated on the stack and then deallocated) memory leakage.

2: Basic Pointers Operations Pointer variables, or just pointers have names, types, and values. The value of a pointer is the address of a memory block. The type of a pointer determines the size of that block (the size is essential to access data stored at that address). For any data type T, for example int, you can define a variable of type "pointer to T", such as "pointer to int : int* p; char* s; // pointer to int // pointer to char

2: Basic Pointers Operations (cont.) Dereferencing using pointer s name, prefixed with the asterisk *. For example, *p is the contents of the memory block that p points to, and *p behaves as an int variable. You can take a non-pointer variable and get a pointer by applying the address operator & to it: int i = 1;...i... // an int variable...&i... // like int pointer, pointing to i int* p; p = &i; // p points to i... *p... // dereferenced p is equal to i

2: Basic Pointers Operations (cont.) C++ provides NULL, but rather than using it, use 0 Two common errors associated with C++ pointers is the use of un-initialized pointers, pointers that point to 0. The language's run-time system does not provide the same safety as Java's exception handling mechanism; instead, your program may continue to execute following the use of an un-initialized pointer, and crash unexpectedly at a later time.

2: Constant Pointers Read these pointer declarations right-to-left: const int* p; a pointer to an integer that is constant; the value of p may change, but the value of *p cannot int* const cp; a constant pointer to integer; the value of *cp can change, but the value of cp cannot const int* const cpc; a constant pointer to a constant integer.

2: Constant Pointers (cont). In some exceptional cases you may want to remove const'ness: const_cast<type>(value) For example, to make pointer p const int* p; point to the value 3 (i.e. to assign 3 to *p), you can use *(const_cast<int*>(p)) = 3;

2: Pointers as Parameters Array parameters are treated like pointers. void maxmin(double* arr, int size, double& max, double& min); void maxminconst(const double* arr, int size, double& max, double& min); const double a[] = {1.5, 3.1}; double max, min; maxmin(a, 2, max, min); // a is const maxminconst(a, 2, max, min); maxmin(const_cast<double*>(a), 2, max, min);

Pointer Parameter 1. Functions that do not modify values pointed to by their pointer parameters should have these parameters specified as const; for example, const double*. This allows us to call the function both with non-constant and constant pointer parameters. 2. Functions that modify their pointer parameters should have these specified as passed by reference.

2: Functions Returning Pointers int* change(int arr[], int size, int i) { // return a pointer to the i-th element if(i < 0 i >= size) return 0; return &arr[i]; } const int* nonchange (const int arr[], int size, int i);... // as above int x[] = {1, 2, 3}; int* i = change(x, 3, 2); *i = 3; // OK, can modify through i const int* j = nonchange(x, 3, 2); cout << *j; *j = 3; // can't assign to a const i = nonchange(x, 3, 2); // can't: non-const

2: C-style Strings and main Function Parameters C++ provides two kinds of strings: string char* - pointer to char, (C-style) C-style strings cannot be avoided in the main function, and for file operations A C-style string can be passed as a parameter of a function: int foo(char* str); Within the body of this function, str is treated as an array of characters (terminated by the zero character). The size of this array is the length of the string, which can be obtained by using the strlen()

2: C-style Strings and main Function Parameters Java C++ Comments about C++ void main( String[] args) int main( int argc, char*argv[]) Integer function with two parameters: - the number of command line parameters - an array of C-style strings representing parameters The name of the program is taken from the command line as argv[0], and therefore argc is always greater than zero

2: C-style Strings and main Function Parameters // File: ex2.5.cpp // Copy words from the input file to the output // file; passing filenames on the command line // Output the total number of words to the standard output // Return 1 if can't open input file; // 2 if can't open output file #include <iostream> #include <fstream> #include <string> int main(int argc, char* argv[]) { // check command line if(argc!= 3) { cerr << "Usage: " << argv[0] << " file1 file2" << endl; return 1; }

} ifstream infile(argv[1]); if(!infile) { Example cerr << "can't open " << argv[1] << endl; return 1; } ofstream outfile(argv[2]); if(!outfile) { cerr << "can't open " << argv[2] << endl; return 2; } string word; long wordcounter = 0; while(infile >> word) { outfile << word << endl; wordcounter++; ifstream and ofstream constructors use C-style strings // copy words // end-of-file } cout << "Read " << wordcounter << " words" << endl; return 0;

2: Static Local Variables Local variables in a function are allocated on the stack, in the socalled instance, or frame for this function. It is sometimes useful to limit the scope but not the lifetime of a variable. void login() { static int counter = 0; counter++; }

2: File Organization and Standard Facilities A Java program: typically consists of multiple files when you compile it, you usually use the name of single file, which contains the main function to be invoked. the Java compiler checks what other files are needed, and whether these files have been recently compiled. All files that have been modified since the last compilation are recompiled, and finally, all compiled files are linked.

2: File Organization and Standard Facilities (cont.) A C++ program: is a set of compilation units, which must be linked together to form the executable code typically consists of multiple files; each file is a unit of compilation. the programmer is responsible for compiling all the necessary files you typically use separate compilation, and a tool such as make to update the executable code. Separate compilation: you can compile parts of your program, where each part is a file

2: Preprocessing and Header Files Related function declarations are typically stored in header files. You typically include the header file containing required declarations. Any line of C++ code that begins with the # (pound symbol) is referred to as a preprocessor command line: include command, which is used to include external files in the current file conditional compilation command, which tells the compiler that a part of the source file is included conditionally

2: Preprocessing and Header Files (cont.) Standard header files #include <filename> User-defined header files: #include "filename.h" (User-defined header file typically have the h extension, for example "screen.h".) These two formats differ in how the specified file is located by the compiler.

2: Preprocessing and Header Files (cont.) Conditional compilation directive is based on the definition of a name, called a macro, which specifies whether this file has already been included. By convention, an include file screen.h will have the macro name SCREEN_H. The header file might look like this: #ifndef SCREEN_H // conditional compilation #define SCREEN_H... // contents of the header file #endif

Include Guards The header file should be conditionally included; for example #ifndef SCREEN_H // conditional compilation #define SCREEN_H... // contents of the header file #endif

2: Namespaces To avoid name collisions, C++ provides namespaces, (similar to Java's packages): Each namespace defines a new scope, and a name used in one namespace does not conflict with the same name used in another namespace. The C++ standard library is defined in a namespace called std. Practically, in all programs, you include the header file: #include <iostream> In order to make every name from this namespace directly available, you specify the namespace with the using keyword: using namespace std;