CS410 – Software Engineering Lecture #3: C++ Basics I

Slides:



Advertisements
Similar presentations
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Advertisements

Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Kernighan/Ritchie: Kelley/Pohl:
Chapter 10.
Pointers A pointer is a variable that contains memory address as its value. A variable directly contains a specific value. A pointer contains an address.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
Chapter 2: Introduction to C++.
Data Types.
February 27, 2014CS410 – Software Engineering Lecture #8: C++ Basics II 1 The vector Container Type When a vector is created, its elements are initialized.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
CSC 107 – Programming For Science. Announcements  Textbook available from library’s closed reserve.
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
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.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
September 20, 2016CS410 – Software Engineering Lecture #5: C++ Basics I 1 C++ Data Types Built-in data typesBuilt-in data types Literal constantsLiteral.
Lecture 2A Data Types Richard Gesick
Chapter 7 Pointers and C-Strings
Chapter 7: User-Defined Functions II
Chapter 1.2 Introduction to C++ Programming
Boston High School Education Project
BASIC ELEMENTS OF A COMPUTER PROGRAM
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Introduction to C++ Systems Programming.
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.
Java Review: Reference Types
Lecture 6 C++ Programming
Pointers and References
Chapter 2: Introduction to C++
C++ for Engineers and Scientists Second Edition
DATA HANDLING.
Object Oriented Programming COP3330 / CGS5409
Chapter 15 Pointers, Dynamic Data, and Reference Types
7 Arrays.
2.1 Parts of a C++ Program.
More About Data Types & Functions
6 Chapter Functions.
Review for Final Exam.
Lecture 18 Arrays and Pointer Arithmetic
Chapter 2: Java Fundamentals
Review for Final Exam.
Chapter 2: Introduction to C++.
7 Arrays.
9-10 Classes: A Deeper Look.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
The C Language: Intro.
Chap 2. Identifiers, Keywords, and Types
ENERGY 211 / CME 211 Lecture 8 October 8, 2008.
9-10 Classes: A Deeper Look.
Presentation transcript:

CS410 – Software Engineering Lecture #3: C++ Basics I Literal Constants A literal string constant is composed of zero or more characters enclosed in double quotation marks. Examples: “” (null string) “x” “hello” “Hi,\nHow are you?\n” February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Literal Constants A string literal can be written across multiple lines. You can use a backslash as the last character on a line to indicate that the string continues on the next line. Example: “This is an \ excellent \ multi-line string literal.” February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Variables Variables provide us with named memory storage that we can write to, read from, and manipulate throughout the course of our program. Each variable has a specific type, which determines the size and layout of its associated memory, the range of values that can be stored, and the set of operations that can be applied to it. Variables are also referred to as objects. February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Variables There are two values associated with a variable: Its data value, which is stored at some memory address. It is also called the rvalue (read value) of the variable. Its address value, indicating the location in memory where its data value is stored. This value is also referred to as the variable’s lvalue (location value). While literal constants also have an rvalue, they do not possess an lvalue. February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Variables Names (identifiers) of variables can be made up of letters, digits, and underscores. Names cannot start with a digit. Notice that C++ compilers distinguish between lower- and uppercase letters. C++ keywords such as if, else, class, etc. cannot be used as variable names. February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Variables Naming conventions: Object-oriented style: Use lowercase letters for names of objects; capitalize the first letter of each embedded word in a multiword identifier. Examples: year, robotCameraModule “Microsoft style”: Also provide type information in object names. Examples: iYear, strFilename General advice: Use mnemonic names, that is, names describing the purpose of the object. February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Variables Initialization of variables: If a variable is defined at global scope, it automatically receives an initial default value (e.g., zero). Variables at local scope and dynamically allocated variables receive an undefined value. It is generally recommended that you assign an initial value to all variables. Example: int loopCounter = 0; Class objects are automatically initialized through their default constructor. February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Variables Further examples of initialization: int year = 2002; string myName = “Peter”; int year(2002); string myName(“Peter”); int loopCounter = int(); // sets loopCounter to 0 double myWeight = double(); // sets myWeight to 0.0 int value = 3*3; int value = GetValue(); February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Pointers A pointer holds the memory address of another object. Through the pointer we can indirectly manipulate the referenced object. Pointers are useful for Creating linked data structures such as trees and lists, management of dynamically allocated objects, and as a function parameter type for passing large objects such as arrays. February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Pointers Every pointer has an associated type. The type of a pointer tells the compiler how to interpret the memory content at the referenced location and how many bytes this interpretation includes. Examples of pointer definitions: int *pointer; int *pointer1, *pointer2; string *myString; February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Pointers The dereference operator (*) dereferences a pointer variable so that we can manipulate the memory content at the location specified by the pointer. The address-of operator (&) provides the memory address (a pointer) of a given object. February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Pointers Example: Correct or incorrect? int var1 = 333, var2 = 444, *pvar1, *pvar2; correct. pvar1 = var1; incorrect. *int  int pvar2 = &var2; correct. *int = *int *pvar1 = var2; correct. int = int *pvar2 = *pvar1 + 100; correct. int = int Question: Considering only correct lines, what is the final value of var2 ? Answer: var2 = 544 February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Pointers Notice that in pointer definitions the ‘*’ symbol indicates the pointer type and is not the dereference operator. Example: int var; int *pvar1 = var; Incorrect! During initialization a pointer can only be assigned an address: int *pvar1 = &var; Correct! February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Pointers You can use pointer arithmetic to iterate through an array: int ia[10]; int *iter = &ia[0]; int *iter_end = &ia[10]; while (iter != iter_end) { do_something_with_value(*iter); ++iter; } February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I References References (aliases) can be used as alternative names for objects. In most cases they are used as formal parameters to a function. A reference type is defined by following the type specifier with the address-of operator. Example: int val1 = 333; int &refVal1 = val1; February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I References A reference must be initialized. Once defined, a reference cannot be made to refer to another object. All operations on the reference are actually applied to the object to which the reference refers. Example: int val1 = 333; int &refVal1 = val1; val1++; refVal1 += 100; cout << “Result: ” << refVal1; Result: 434 February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I The C++ string Type To use the C++ string type, you must include its associated header file: #include <string> Different ways to initialize strings: string myString(“Hello folks!”); string myOtherString(myString); string myFinalString; // empty string The length of a string is returned by its size() operation (without the terminating null character): cout << myString.size(); 12 February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I The C++ string Type We can use the empty() operation to find out whether a string is empty: bool isStringEmpty = myString.empty(); Use the equality operator to check whether two strings are equal: if (myString == myOtherString) cout << “Wow, the strings are equal.”; Copy one string to another with the assignment operator: myFinalString = myOtherString; February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I The C++ string Type Use the plus operator to concatenate strings: string s1 = “Wow! ”, s2 = “Ouch! ”; const char *s3 = “Yuck! ” s2 += s1 + s3 + s2; cout << s2; Ouch! Wow! Yuck! Ouch! February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I The const Qualifier The const type qualifier transforms an object into a constant. Example: const double pi = 3.1416; Constants allow you to store parameters in well- defined places in your code Constants have an associated type. Constants must be initialized. Constants cannot be modified after their definition. Constants replace the #define “technique” in C. February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Default Arguments Notice that only trailing parameters of a function can have default values. This rule allows the compiler to know which arguments are defaulted when the function is called with fewer than its complete set of arguments. Examples: void F1(int i, int j = 7); legal void F2(int i = 3, int j); illegal void F3(int i, int j = 3, int k = 7); legal void F4(int i = 1, int j = 2, int k = 3); legal void F5(int i, int j = 2, int k); illegal February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

Functions as Arguments Functions in C++ can be thought of as the addresses of the compiled code residing in memory. Functions are therefore a form of pointer. Functions can be passed as a pointer-value argument into another function. February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

Functions as Arguments double F(double x) { return (x*x + 1.0/x); } void plot(double Fcn(double), double x0, double incr, int n) for (int i = 0; i < n; i++) cout << “x: “ << x0 << “ f(x): “ << Fcn(x0) << endl; x0 += incr; int main() plot(F, 0.01, 0.01, 100); return 0; February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

Overloading Functions Overloading refers to using the same name for multiple meanings of an operator or a function. Example: double Average(const int a[], int size) { int sum = 0; for (int i = 0; i < size; ++i) sum += a[i]; return static_cast<double> (sum) / size; } double Average(const double a[], int size) { double sum = 0.0; for (int i = 0; i < size; ++i) sum += a[i]; return (sum / size); } February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

Overloading Functions The following code shows how Average() is invoked: int main() { int a[5] = {1, 2, 3, 4, 5}; double b[5] = {1.1, 2.2, 3.3, 4.4, 5.5}; cout << Average(a, 5) << “ int average” << endl; cout << Average(b, 5) << “ double average” << endl; return 0; } 3 int average 3.3 double average February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Inlining C++ provides the keyword inline to preface a function declaration. For functions declared as inline, the compiler will generate inline code instead of function calls. Inline functions lead to increased time efficiency and decreased memory efficiency. Question: How about recursive functions? Answer: There are no recursive inline functions because they would require infinite memory. February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Inlining Inlining has a similar effect as macro expansion: Inlining example: inline double cube(double x) { return (x * x * x); } Macro example: #define CUBE(X) ((X)*(X)*(X)) February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Inlining So what is the difference between inlining and macro expansion? Answer: Macro expansion provides no type safety as is given by the C++ parameter-passing mechanism. Therefore, it is advisable to use inlining instead of macro expansion. February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Enumeration Types Sometimes you may want to define for your object a set of states or actions. For example, you could define the following states for a Student Admonisher Robot: observeStudent shoutAtStudent followStudent rechargeBattery February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Enumeration Types Using the const qualifier, you could define the following constants: const int observeStudent = 1; const int shoutAtStudent = 2; const int followStudent = 3; const int rechargeBattery = 4; A function SetRobotState could then be defined as follows: bool SetRobotState(int newState) { … int currentState = newState; return executionSuccessful; } February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Enumeration Types However, mapping states onto integers has certain disadvantages: You cannot restrict the range of values that are passed to SetRobotState. There is no useful typing – if you define individual sets of states for multiple objects, each object could formally be set to any of these states, not only its individual ones. This problem can be solved with enumeration types. February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Enumeration Types Enumeration types can be defined as follows: enum robotState {observeStudent = 1, shoutAtStudent, followStudent, rechargeBattery}; This way we defined a new type robotState that can only assume four different values. These values still correspond to integers. For example, cout << followStudent; gives you the output ‘3’. February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I

CS410 – Software Engineering Lecture #3: C++ Basics I Enumeration Types However, we are now able to restrict the values that are passed to SetRobotState to the four legal ones: bool SetRobotState(robotState newState) { … robotState currentState = newState; return executionSuccessful; } Any attempt to call SetRobotState with an integer value or a value of a different enumeration type will cause an error at compile time. February 26, 2019 CS410 – Software Engineering Lecture #3: C++ Basics I