ENERGY 211 / CME 211. Functions

Similar documents
UEE1302 (1102) F10: Introduction to Computers and Programming

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Functions and Recursion

Pointers, Dynamic Data, and Reference Types

Chapter 10 Introduction to Classes

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

CS201 Some Important Definitions

Programming, numerics and optimization

Structures, Unions Alignment, Padding, Bit Fields Access, Initialization Compound Literals Opaque Structures Summary. Structures

CS304 Object Oriented Programming Final Term

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference


COMP322 - Introduction to C++

Fast Introduction to Object Oriented Programming and C++

QUIZ Lesson 4. Exercise 4: Write an if statement that assigns the value of x to the variable y if x is in between 1 and 20, otherwise y is unchanged.

Lecture 2 Tao Wang 1

Lecture-5. Miscellaneous topics Templates. W3101: Programming Languages C++ Ramana Isukapalli

Chapter 4: Subprograms Functions for Problem Solving. Mr. Dave Clausen La Cañada High School

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:

G Programming Languages - Fall 2012

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

Lecture 18 Tao Wang 1

Programming Languages

Interview Questions of C++

Fundamental Concepts and Definitions

AN OVERVIEW OF C++ 1

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

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Informatica 3 Syntax and Semantics

BITG 1113: Function (Part 2) LECTURE 5

Names, Scope, and Bindings

Chapter 1. Section 1.4 Subprograms or functions. CS 50 - Hathairat Rattanasook

CS3157: Advanced Programming. Outline

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:

UNIT- 3 Introduction to C++

Tokens, Expressions and Control Structures

CSI33 Data Structures

Intermediate Programming & Design (C++) Classes in C++

AS08-C++ and Assembly Calling and Returning. CS220 Logic Design AS08-C++ and Assembly. AS08-C++ and Assembly Calling Conventions

Midterm Review. PIC 10B Spring 2018

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Introduction to Programming (Java) 4/12

Getting started with C++ (Part 2)

Names, Scope, and Bindings

Absolute C++ Walter Savitch

CSE 303: Concepts and Tools for Software Development

C++ For Science and Engineering Lecture 15

Introduction to C++ with content from

Lecture 5: Methods CS2301

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

Your first C++ program

DECLARAING AND INITIALIZING POINTERS

Object Oriented Design

University of Kelaniya Sri Lanka

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

Name: Username: I. 20. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

W3101: Programming Languages C++ Ramana Isukapalli

C++ Arrays. Arrays: The Basics. Areas for Discussion. Arrays: The Basics Strings and Arrays of Characters Array Parameters

TDDE18 & 726G77. Functions

Jim Lambers ENERGY 211 / CME 211 Autumn Quarter Programming Project 2

C++ Quick Guide. Advertisements

Polymorphism Part 1 1

CS3215. Outline: 1. Introduction 2. C++ language features 3. C++ program organization

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Lecture 3: C Programm

Functions. Arizona State University 1

C++ Programming for Non-C Programmers. Supplement

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

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

More on Functions. Lecture 7 COP 3014 Spring February 11, 2018

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Programming Using Java (98-388)

by Pearson Education, Inc. All Rights Reserved.

CSI33 Data Structures

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Introduction to C++ Systems Programming

STRUCTURING OF PROGRAM

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

High Performance Computing and Programming, Lecture 3

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );

Working with Strings. Lecture 2. Hartmut Kaiser. hkaiser/spring_2015/csc1254.html

Variables. Data Types.

Separate Compilation Model

Week 8: Operator overloading

Classes and Objects. Class scope: - private members are only accessible by the class methods.

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 12, FALL 2012

CS201- Introduction to Programming Current Quizzes

C++ C and C++ C++ fundamental types. C++ enumeration. To quote Bjarne Stroustrup: 5. Overloading Namespaces Classes

Transcription:

ENERGY 211 / CME 211 Lecture 8 October 8, 2008 1 Functions So far, we have seen programs in which all code resides within a main function Complex programs consist of subprograms that perform particular tasks In C++, these subprograms are called functions A function accepts inputs, called arguments, and computes a return value that is the function's output 2 1

Designing a Function Decompose application into subtasks How do subtasks interact? If subtask A delegates work to subtask B, what data does A need to furnish B? What data does A require from B to complete its task? These questions determine a function's declaration Implementing each subtask completes function's definition 3 Calling a Function The input values passed to a function are the actual parameters (arguments) Inside the function, these values are the formal parameters (parameters) A function's definition includes its return type, name, formal parameters with types, and statements (the body) Its declaration is all this except the body If a function is called before it is defined, then it must be declared first 4 2

Procedures vs. Functions Many programming languages have procedures: subroutines that perform actions but do not return a value They also have distinct subprograms called functions, which compute output values from input values In C/C++, all subprograms are functions Can specify a return type of void, so that no value is returned, and the function is essentially a procedure 5 Overloading Functions Often functions perform similar tasks on inputs of different types Shouldn't require distinct functions Functions can be overloaded with different definitions for different inputs When function is called, compiler determines which definition to use Cannot overload with definitions that have same parameter types but different return types 6 3

The inline Keyword Many functions have a simple definition, such as void printint(ints) {cout<<s;} When compiling, the overhead of a function call can be costly, but using a function is still best for modularity Preceding declaration with the inline keyword asks the compiler to replace calls to printint with its code 7 Pass by Value or Reference? Example: in voidf(stringx); the argument x is passed by value In f(y); the value of y is copied to x Any change in x does not affect y In voidg(string&str); the argument s is passed by reference In g(s); the address of s is passed and assigned to str, so str is a reference to s A change in str is reflected in s 8 4

The const Qualifier Calling voidf(string&s); by f("hello"); is not valid "Hello" is an array of char, which supports literals, so allowing this implies a literal's value could be changed! Use void f(conststring&s); to indicate s is not changed by f(), or create a string object and pass that const helps the compiler optimize code by reducing possible memory writes 9 The return Statement If a function is not of type void, then it should return a value, using a return statement Form: return expr; where expr is the value to be returned A return statement causes an immediate exit from the function! When function exits, local, non-static variables are deallocated, so never return a reference to a local object! 10 5

static Variables Normally, variables local to a function are destroyed when the function exits If a local variable is declared static, it persists throughout execution Value is retained, and available when function is called again Beware: initialization only happens once, when the function is first called! Global static variables can only be used in the file in which they are declared 11 Default Arguments Suppose we declare, for example, int f(int arg1, int optarg = 0); If we call f as follows: x=f(3); then inside f(), the value of optarg is 0 We call optarg a default argument An argument cannot be a default argument unless all subsequent arguments are also default Using defaults reduces overloading 12 6

Separate Header Files So far, we have declared and defined functions in the same file What if a function f() defined in a file f.cpp needs to call a function g() defined in another file g.cpp? Solution: declare g() in a header file, for example, g.h, and in f.cpp, use #include"g.h" Header files typically have a.h extension (sometimes.hpp) 13 Naming New Types C++ provides many ways of creating new types from existing ones: pointers to types, arrays of types, functions with return and argument types, etc. Types are complicated to describe The typedef keyword allows simple names to be given to these types Form (in most cases): typedef type-expression type-name; where type-name is the new name 14 7

Uses of typedef Opaque type names: to hide details about a type from a user, for example typedef unsigned int size_t; Descriptive: to convey interpretation of data: typedef int years; Simpler: to condense complex type expressions such as typedefint (*func_type)(int); where func_type is a pointer to a function that accepts, and returns, an int 15 Next Time All about streams and files: Console, file and string streams Stream manipulators Object persistence Project 2 distribution! 16 8