csci 1730 — fall 2016 systems programming · cotterell - csci 1730 - systems programming...

428
Cotterell - CSCI 1730 - Systems Programming CSCI 1730 — Fall 2016 Systems Programming Michael E. Cotterell a.k.a. Supa’ Mike Comic Link: http://dilbert.com/strip/1995-06-24 If this is Chemistry 430, please do NOT sit near the very back. The room is huge.

Upload: others

Post on 02-Jun-2020

14 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

CSCI 1730 — Fall 2016

Systems Programming

Michael E. Cotterella.k.a. Supa’ Mike

Comic Link: http://dilbert.com/strip/1995-06-24

If this is Chemistry 430, please do NOT sit near the very back. The room is huge.

Page 2: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

–Supa’ Mike, on the previous slide.

“If this is Chemistry 430, please do NOT sit near the very back. The room is huge.”

Page 3: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 3030 - Computing, Ethics, and Society

Michael E. Cotterell❖ Faculty Instructor & Ph.D. student in Computer

Science at UGA.

❖ Received B.S. in CS from UGA in May 2011.

❖ As an undergraduate, I served as the VP of UGA ACM.

❖ I’ve interned at the National Renewable Energy Lab (NREL) in Colorado, where I conducted computer science research on formal ontologies for Energy Systems Integration and Energy Informatics.

❖ I’ve also worked at the UGA Institute of Bioinformatics (IOB), where I helped i) develop and integrate suggestion algorithms for scientific workflows; and ii) setup a virtualized server environment.

Don’t call me, “doctor,” since I don’t have my Ph.D. yet. Acceptable names include:• Supa’ Mike• Michael• Mr. Cotterell (but that’s my dad’s name)

❖ Disc Golf

❖ Scala

❖ GitHub

❖ Emacs

Page 4: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Office Hours❖ My office hours are

❖ MW 10:00 AM -- 11:00 AM in Boyd 610B

❖ TR 02:00 PM -- 03:00 PM in Boyd 610B

❖ TA Office Hours will be posted next week.

Page 5: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Meeting Times❖ Unless cleared by the instructor, you should only attend

the lecture breakout sections for which you are assigned.

Page 6: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Important Links❖ eLC: http://elc.uga.edu/

❖ Piazza: https://piazza.com/uga/fall2016/csci1730/home

Page 7: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Course Description❖ This four-hour course covers the basics of UNIX

Systems Programming, including file and directory structures, basic and advanced file I/O, process creation and management, and interprocess communication.

❖ Throughout the semester, the language basics of C and C++ will be covered in order familiarize students with the use of C and C++ in systems programming.

Page 8: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Systems Programmers

Margaret Hamilton

LinusTorvalds

RichardStallman

Page 9: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Required Textbooks

You do NOT need to purchase MyProgrammingLab online access for this class.

Page 10: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Assigned Readings

❖ You are responsible for any assigned/recommended readings.

Page 11: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

@TODO❖ Review / Read

❖ DEITEL 1–2, 4–5, & 6.1–6.5

❖ UNIX Tutorial for Beginners

❖ http://www.ee.surrey.ac.uk/Teaching/Unix/unixintro.html

❖ http://www.ee.surrey.ac.uk/Teaching/Unix/unix1.html

❖ http://www.ee.surrey.ac.uk/Teaching/Unix/unix2.html

❖ http://www.ee.surrey.ac.uk/Teaching/Unix/unix3.html

❖ Definitely Read

❖ APUE 1—2

❖ DEITEL 22.5—22.6

Page 12: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Grading ScalePoints Letter Grade Note

[94, ∞) A

[90, 94) A-

[87, 90) B+

[84, 87) B

[80, 84) B-

[77, 80) C+

[74, 77) C

[70, 74) C- Will not satisfy requirements that require a C or better.

[65, 70) D Passing

[ 0, 65) F Failing

Page 13: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Tentative Grade BreakdownCategory Points

Breakout Labs 30%

Regular Projects (x3) 30%

Exam 1 - 2016-09-29 @ 6PM 15%

Exam 2 - 2016-12-01 @ 6PM 15%

Final Project 10%

100%

If you have a mass exam conflict, then you will need to register for a make-up session. More information on this will be available closer to the exam

dates.

Page 14: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exercises & Programming Assignments

❖ Written solutions to exercises are to be submitted in plain text using the Markdown format.

❖ The programming assignments will be written in C++ or C using Linux (on nike.cs.uga.edu). You are responsible to make sure that your program compiles and runs correctly on Nike.

❖ All projects are to be completed individually unless otherwise (and explicitly) noted.

❖ Breakout assignments do have a collaborative aspect to them, however, actual code implementation must be done individually.

Page 15: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Academic Honesty

❖ As a University of Georgia student, you have agreed to abide by the University's academic honesty policy, "A Culture of Honesty," and the Student Honor Code.

❖ All academic work must meet the standards described in "A Culture of Honesty" found at: www.uga.edu/honesty.

❖ Lack of knowledge of the academic honesty policy is not a reasonable explanation for a violation.

❖ Questions related to course assignments and the academic honesty policy should be directed to the instructor.

Page 16: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

More on Academic Honesty

❖ You also agree not to make any portion of your assignments for this class publicly available for others to view. This includes, but is not limited to, posting snippets of your code on help websites.

❖ Engaging in activities similar to this will be seen as either giving or receiving unauthorized assistance as described in the Student Honor Code.

Page 17: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Q&A Websites❖ With regard to question and answer websites (e.g.,

StackOverflow, Yahoo Answers, etc.), you may ask general questions about programming on such websites that relate to your assignments in this class, however, you must phrase such questions in a way that make them independent of the specific problem you are having.

❖ If you need specific help with portions of your code, then you must consult with the instructor or teaching assistants first (unless expressly and explicitly stated otherwise in the assignment description).

Page 18: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Copy, Paste & Plagiarism❖ If you copy or extend material from the Web (in any fashion)

or other sources and incorporate that material into the submission for one of your assignments then you must cite where you got the code from in order to avoid plagiarism.

❖ A citation should be included in the in an inline comment nearest the code being copied.

❖ That being said, you should be able to solve all the coding assignments from scratch. Being unable to do so will affect your exam performance.

Page 19: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

More on Academic Honesty

❖ All faculty, staff and students are encouraged to report all suspected cases of academic dishonesty.

❖ All cases of SUSPECTED academic dishonesty (cheating) will be referred to the Office of the Vice President for Instruction (OVPI).

❖ Penalties imposed by OVPI may include a failing grade in the course and a notation on the student's transcript. Repeated violations are punishable by expulsion from the University.

Page 20: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Re-grades

❖ You may request a re-grade of any graded item any time within 7 calendar days (i.e., not 7 class days) of receiving the grade.

❖ To make a request, you should submit a written justification for the request via email to the instructor.

Page 21: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Late Work

❖ Work that is turned in late is subject to an immediate 20% deduction in the number of potential points plus an additional 20% deduction for each 24 hour period (including weekends) that has passed since the time when the assignment was due.

❖ For example, if a project is worth 100 points and you turn it in late but less than 24 hours past the deadline, then the highest grade you can potentially earn is an 80/100.

Page 22: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

More on Late Work

❖ If you turn work in late, you should email both the instructor and the TA, informing them about which assignment was turned in late as well as a description about why it is late.

❖ Late work that is received without an email on record to both the instructor and the TA will not be accepted.

Page 23: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Make-up Exams

❖ Students may request to take an exam prior to the examination date.

❖ This request must be made at least one week prior to the scheduled examination date.

❖ Students who do not make such a request and are not in attendance on the examination date have an opportunity to take the exam at a different time only under exceptional circumstances, such as family or medical emergencies, and must have the absence approved by the instructor.

Page 24: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Make-up Quizzes

❖ Students may request to make up a Quiz only under exceptional circumstances, such as family or medical emergencies, and must have a way to verify their exception.

Page 25: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Laptops, Phones, etc…❖ Access to the Internet can be a valuable aid to the classroom learning

environment. ❖ Students are encouraged to use laptops, smart phones, and other

devices in order to explore concepts related to course discussions and topics.

❖ Students are discouraged from using technology in ways that distract from the learning community. If found doing so, will be asked to leave the classroom for the day and will not get credit for attendance that class period if attendance was taken.❖ Please, no Facebook, texting, or working on stuff for other classes.❖ If you’re going to be on Reddit, at least be in a course-appropriate

subreddit (e.g., /r/programming, /r/java, /r/compsci, etc.). Remember, the narwhal bacons at midnight.

Page 26: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

❖ This term we will be using Piazza for class discussion. The system is highly catered to getting you help fast and efficiently from classmates, the TA, and myself. Rather than emailing questions to the teaching staff, I encourage you to post your questions on Piazza. If you have any problems or feedback for the developers, email [email protected].

❖ Find our class page at: https://piazza.com/uga/fall2016/csci1730/home

Page 27: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Additional Information

❖ Students with a disability or health-related issue who need a class accommodation should make an appointment to speak with the instructor as soon as possible.

❖ When emailing the instructor or TA, please include a [cs1730] tag in the subject line.

Page 28: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Breakout StructureNO COMPUTER USE

1. At the beginning of class, the TA (or me) will introduce a problem or exercise.

2. Then, you’ll break up into groups and brainstorm and plan out what needs to be done in order to solve the problem.

NOW YOU CAN USE A COMPUTER

3. Next, you’ll log into eLC and submit a version of your group’s brainstorm written in your own words. Feel free to add onto it. Please include the last names of each group member.

4. For the remainder of the period, you work individually on the assignment. Assignments must be submitted via Nike before 10AM on the day of the next breakout.

Page 29: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

nike.cs.uga.edu❖ You should have an account. If don’t have your username

and password then you’ll need to go to Boyd 307 (more on that later).

❖ All programming assignments will be submitted via Nike.

❖ All programming assignments will be graded on Nike (so make sure they work on Nike before submitting them).

❖ You should work on your assignments directly on Nike.

❖ You can connect to nike via an SSH client.

Page 30: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Getting Your Nike Password❖ The Boyd 307 lab should open next week.

❖ New students will be able to pick up their Nike passwords at that time(bring ID.)

❖ It takes a couple of days ofter registration for new accounts to be made. Students that have signed up for CSCI 1302 or higher will have their accounts reactivated.

❖ In case of password issues students can email [email protected] or stop by Boyd 307.

❖ The reset password notification is send to the student's UGAmail account with a link to sendfiles.uga.edu.

Page 31: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

C and C++ for Java Programmers

❖ Java, C and C++ have a similar syntax for basic concepts.

❖ Most of the basic constructs like if statements, loops, function syntax, switch case statements and concepts like recursion are still valid.

❖ Many other concepts like the syntax for comments, and the idea of static class variables, also hold in both Java and C++.

Page 32: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Toolset and Compilation Model

❖ In Java, you need a Java Virtual Machine (JVM) and a Java compiler, and the Java compiler produces class files that the JVM understands.

❖ In C and C++, you don't need a VM—the result of a build is an executable file that will run on the native OS.

❖ Similar to Java, you can individually compile source files into object files, but the act of creating the executable file is called linking.

Page 33: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Basics of a Typical C++ Environment

❖ Phases of C++ Programs:

1.Edit

2.Preprocess

3.Compile

4.Link

5.Load

6.Execute

Loader

PrimaryMemory

Program is created inthe editor and storedon disk.

Preprocessor programprocesses the code.

Loader puts programin memory.

CPU takes eachinstruction andexecutes it, possiblystoring new datavalues as the programexecutes.

Compiler

Compiler createsobject code and storesit on disk.

Linker links the objectcode with the libraries,creates a.out andstores it on disk

Editor

Preprocessor

Linker

CPU

PrimaryMemory

.

.

.

.

.

.

.

.

.

.

.

.

Disk

Disk

Disk

Disk

Disk

Page 34: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Import vs the C++ Preprocessor❖ One of the most noticeable differences in compilation is that Java uses imports and

does not have a preprocessor—if you're coming from Java, you're used to using import statements to include references to classes from the Java class library.

❖ In C and C++, you instead include header files that provide declarations for library objects, and you may also need to use using declarations to provide short names.

❖ The equivalent of something likeimport java.lang.String;

❖ In C++ would be:#include <string>

❖ You’ll find that C and C++ takes much longer to compile that Java because include statements require a great deal of parsing.

Page 35: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

hello.cpp

// my first C++ program!#include <iostream>#include <cstdlib>int main() { std::cout << “Hello World!” << std::endl; return EXIT_SUCCESS;} // main

Page 36: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

hello.cpp

// my first C++ program!#include <iostream>#include <cstdlib>int main() { std::cout << “Hello World!” << std::endl; return EXIT_SUCCESS;} // main

Page 37: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

hello.cpp// my first C++ program!#include <iostream>#include <cstdlib>int main() { std::cout << “Hello World!” << std::endl; return EXIT_SUCCESS;} // main

Comments

Written between /* and */ or following a //.

Improve program readability and do not cause the computer to perform any action.

Page 38: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

hello.cpp// my first C++ program!#include <iostream>#include <cstdlib>int main() { std::cout << “Hello World!” << std::endl; return EXIT_SUCCESS;} // main

preprocessor directive

Message to the C++ preprocessor.Lines beginning with # are preprocessor

directives.#include <iostream> tells the preprocessor to include the contents of the file <iostream>, which includes input/output operations (such

as printing to the screen).

Page 39: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

hello.cpp// my first C++ program!#include <iostream>#include <cstdlib>int main() { std::cout << “Hello World!” << std::endl; return EXIT_SUCCESS;} // main

C++ programs contain one or more functions, one of which must be main

Parenthesis are used to indicate a functionint means that main "returns" an integer value.

Page 40: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

hello.cpp// my first C++ program!#include <iostream>#include <cstdlib>int main() { std::cout << “Hello World!” << std::endl; return EXIT_SUCCESS;} // main

Prints the string of characters contained between the quotation marks.

The entire line, including cout, the << operator, the string "Welcome to C++!”, endl and the semicolon (;), is

called a statement.

All statements must end with a semicolon.

Page 41: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

hello.cpp// my first C++ program!#include <iostream>#include <cstdlib>int main() { std::cout << “Hello World!” << std::endl; return EXIT_SUCCESS;} // main return is a way to exit a function from a function.

return 0, in this case, means that the program terminated normally.

EXIT_SUCCESS is a constant for 0, made available by including

<cstdlib>

Page 42: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Inside our Example Program• cout

❖ Standard output stream object❖ “Connected” to the screen❖ std:: specifies the "namespace" which cout belongs to

• << ❖ Stream insertion operator ❖ Value to the right of the operator (right operand) inserted into

output stream (which is connected to the screen)– cout << “Welcome to C++!\n”;

• endl ❖ A constant for “\n”, the escaped new line character.

Page 43: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Using Namespace std❖ If you have seen C++ code before, you may have seen cout being used instead of std::cout. Both name the same object:

❖ the first one uses its unqualified name (cout), while

❖ the second use its qualified name, i.e., it qualifies it directly within the namespace std (as std::cout).

❖ cout is part of the standard library, and all the elements in the standard C++ library are declared within what is a called a namespace: the namespace std.

Page 44: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Using Namespace std❖ In order to refer to the elements in the std namespace a program

shall either qualify each and every use of elements of the library (as we have done by prefixing cout with std::), or introduce visibility of its components.

❖ The most typical way to introduce visibility of these components is by means of using declarations:using namespace std;

❖ The above declaration allows all elements in the std namespace to be accessed in an unqualified manner (without the std:: prefix).

Page 45: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Using Namespace std

❖ Both ways of accessing the elements of the std namespace (explicit qualification and using declarations) are valid in C++ and produce the exact same behavior.

❖ It is important to note that explicit qualification is the only way to guarantee that name collisions never happen.

❖ We will discuss namespaces in more detail a later point in time.

Page 46: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

@TODO❖ Review / Read

❖ DEITEL 1–2, 4–5, & 6.1–6.5

❖ UNIX Tutorial for Beginners

❖ http://www.ee.surrey.ac.uk/Teaching/Unix/unixintro.html

❖ http://www.ee.surrey.ac.uk/Teaching/Unix/unix1.html

❖ http://www.ee.surrey.ac.uk/Teaching/Unix/unix2.html

❖ http://www.ee.surrey.ac.uk/Teaching/Unix/unix3.html

❖ Definitely Read

❖ APUE 1—2

❖ DEITEL 22.5—22.6

Page 47: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Meeting TimesThis Week’s Readings APUE 1–2 DEITEL 22.5–22.6

Next Week’s ReadingsDEITEL 6.6, 6.10–6.21 DEITEL 8.1–8.12

Page 48: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Updated Grade BreakdownCategory Points

Breakouts 30%

Quizzes 10%

Regular Projects 30%

Exam 1 10%

Exam 2 10%

Final Project 10%

100%

Page 49: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Live Demo

❖ Login to Nike

❖ Simple “Hello World” in C++

❖ Compile

❖ Link

❖ Makefiles

Page 50: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Meeting TimesThis Week’s Readings APUE 1–2 DEITEL 22.5–22.6

Next Week’s ReadingsDEITEL 6.6, 6.10–6.21 DEITEL 8.1–8.12

Page 51: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

@TODO❖ Nike username/password

❖ Problems? —> [email protected]

❖ Setup your Nike account —> According to Lab 01

Page 52: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Identifiers❖ A valid identifier is a sequence of one or more letters, digits, or

underscore characters (_).

❖ Spaces, punctuation marks, and symbols cannot be part of an identifier. In addition, identifiers shall always begin with a letter.

❖ They can also begin with an underline character (_), but such identifiers are -on most cases- considered reserved for compiler-specific keywords or external identifiers, as well as identifiers containing two successive underscore characters anywhere.

❖ In no case can they begin with a digit.

Page 53: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

C++ Reserved Identifiers❖ C++ uses a number of keywords to identify operations and data descriptions;

therefore, identifiers created by a programmer cannot match these keywords.

❖ The standard reserved keywords that cannot be used for programmer created identifiers are:❖ alignas, alignof, and, and_eq, asm, auto, bitand, bitor, bool, break,

case, catch, char, char16_t, char32_t, class, compl, const, constexpr, const_cast, continue, decltype, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, noexcept, not, not_eq, nullptr, operator, or, or_eq, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_assert, static_cast, struct, switch, template, this, thread_local, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while, xor, xor_eq

❖ Specific compilers may also have additional specific reserved keywords.

Page 54: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Case Sensitivity

❖ The C++ language is a "case sensitive" language.

❖ That means that an identifier written in capital letters is not equivalent to another one with the same name but written in small letters.

❖ Thus, for example, the RESULT variable is not the same as the result variable or the Result variable. These are three different identifiers identifying three different variables.

Page 55: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Fundamental Data Types❖ Fundamental data types are basic types implemented directly by the language

that represent the basic storage units supported natively by most systems. They can mainly be classified into:❖ Character types: They can represent a single character, such as 'A' or '$'. The most basic

type is char, which is a one-byte character. Other types are also provided for wider characters.

❖ Numerical integer types: They can store a whole number value, such as 7 or 1024. They exist in a variety of sizes, and can either be signed or unsigned, depending on whether they support negative values or not.

❖ Floating-point types: They can represent real values, such as 3.14 or 0.01, with different levels of precision, depending on which of the three floating-point types is used.

❖ Boolean type: The boolean type, known in C++ as bool, can only represent one of two states, true or false.

Page 56: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

The names of certain integer types can be abbreviated without their signed and int components - only the part not in italics is required to identify the type, the

part in italics is optional. I.e., signed short int can be abbreviated as signed short, short int, or simply short; they all identify the same fundamental type.

Fundamental Data Types

Page 57: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Type Sizes❖ Except for char (which has a size of exactly one byte), none of the

fundamental types has a standard size specified (but a minimum size, at most).

❖ Therefore, the type is not required (and in many cases is not) exactly this minimum size.

❖ This does not mean that these types are of an undetermined size, but that there is no standard size across all compilers and machines; each compiler implementation may specify the sizes for these types that fit the best the architecture where the program is going to run.

❖ This rather generic size specification for types gives the C++ language a lot of flexibility to be adapted to work optimally in all kinds of platforms, both present and future.

Page 58: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Type Sizes❖ Type sizes above are expressed in bits; the more bits a

type has, the more distinct values it can represent, but at the same time, also consumes more space in memory:

Page 59: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Integer Types❖ For integer types, having more representable values means that the range of

values they can represent is greater.

❖ For example, a 16-bit unsigned integer would be able to represent 65536 distinct values in the range 0 to 65535, while its signed counterpart would be able to represent, on most cases, values between -32768 and 32767.

❖ Note that the range of positive values is approximately halved in signed types compared to unsigned types, due to the fact that one of the 16 bits is used for the sign.

❖ This is a relatively modest difference in range, and seldom justifies the use of unsigned types based purely on the range of positive values they can represent.

Page 60: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Floating Point Types❖ For floating-point types, the size affects their precision,

by having more or less bits for their significant and exponent.

❖ If the size or precision of the type is not a concern, then char, int, and double are typically selected to represent characters, integers, and floating-point values, respectively.

❖ The other arithmetic types we saw in the chart are only used in very particular cases.

Page 61: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Type Sizes

❖ The properties of fundamental types in a particular system and compiler implementation can be obtained by using the numeric_limits classes (see standard header <limits>).

❖ If for some reason, types of specific sizes are needed, the library defines certain fixed-size type aliases in header <cstdint>.

❖ We’ll go into the particulars of this later.

Page 62: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Type Sizes❖ To get the number of bytes for a type, you can use the sizeof

function.

❖ For examplestd::cout << sizeof(int) << std::endl;

❖ Should produce (on most systems)

4

The value returned by sizeof is a compile-time constant, so it is always determined before program execution.

Page 63: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Bitwise Operators❖ Bitwise operators modify variables considering the bit

patterns that represent the values they store.

❖ In other words, bitwise operators manipulate individual bits within a variable.

Page 64: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Bitwise Operators

❖ In the following examples, we will largely be working with 4-bit binary values. This is for the sake of convenience and keeping the examples simple. In C++, the number of bits used will be based on the size of the data type (8 bits per byte).

Operator Symbol Form Operation

left shift << x << y all bits in x shifted left y bits

right shift >> x >> y all bits in x shifted right y bits

bitwise NOT ~ ~x all bits in x flipped

bitwise AND & x & y each bit in x AND each bit in y

bitwise OR | x | y each bit in x OR each bit in y

bitwise XOR ^ x ^ y each bit in x XOR each bit in y

Page 65: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Left Shift and Right Shift❖ The << operator shifts bits to the left.

❖ For example, consider the number 3, which is binary 0011. Left shifting by 1 (3 << 1) changes 0011 to 0110, which is decimal 6.

❖ Note how each bit moved 1 place to the left. Left shifting by 2 (3 << 2) changes 0011 to 1100, which is decimal 12.

❖ Left shifting by 3 (3 << 3) changes 0011 to 1000. Note that we shifted a bit off the end of the number! Bits that are shifted off the end of the binary number are lost.

❖ This behavior is dependent on the size of the variable. If more than 4 bits are available, then we would not have lost a bit in this example.

❖ The >> operator shifts bits to the right. ❖ Right shifting by 1 (3 >> 1) changes 0011 to 0001, or decimal 1. The rightmost bit

shifted off the end and was lost!

Page 66: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Shifting Exampleunsigned int n = 4;n = n << 1; // n will be 8

❖ Rule: When dealing with bit operators, use unsigned variables.

Page 67: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Multiplying and Dividing by Powers of Two

❖ Consider what a simple unsigned 4 bit integer data type usually means…

b3b2b1b0 in binary is (b3 * 23) + (b2 * 22) + (b1 * 21) + (b0 * 20) in decimal

❖ Shifting to the left x times multiplies each term by 2x. We can use the distributive property to show that this multiplies the whole number by 2x.

❖ Shifting to the right x times divides each term by 2x.

Page 68: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Bitwise NOT❖ The bitwise NOT operator (~) is perhaps the easiest to

understand of all the bitwise operators.

❖ It simply flips each bit from a 0 to a 1, or vice versa.

❖ Note that the result of a bitwise NOT is dependent on what size your data type is! ❖ For example, with 4 bits, ~4 (0100 binary) evaluates to 1011,

which is 11 in decimal.

❖ In an 8 bit data type (such as an unsigned char), ~4 (represented as ~0000 0100) evaluates to 1111 1011, which is 251 in decimal!

Page 69: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Bitwise AND, OR, and XOR❖ 5 & 60 1 0 1 // 50 1 1 0 // 6————————————0 1 0 0 // 4

❖ 5 | 60 1 0 1 // 50 1 1 0 // 6————————————0 1 1 1 // 7

❖ 5 ^ 60 1 0 1 // 50 1 1 0 // 6————————————0 0 1 1 // 3

❖ If the bits in a column are all 1, then the resulting bit is set to 1, otherwise 0.

❖ If there is a 1 bit in a column, then the resulting bit is set to 1, otherwise 0.

❖ If the bits in a column are not equal to each other, then the resulting bit is set to 1, otherwise 0.

Page 70: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Compound XOR❖ It is also possible to evaluate compound XOR expression

column style, such as 1 ^ 3 ^ 7.

❖ If there are an even number of 1 bits in a column, the result is 0.

❖ If there are an odd number of 1 bits in a column, the result is 1.0 0 0 1 // 10 0 1 1 // 30 1 1 1 // 7————————————0 1 0 1 // 5

Page 71: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Bitwise Assignment OperatorsOperator Symbol Form Operation

left shift assignment <<= x <<= y shift x left by y bits

right shift assignment >>= x >>= y shift x right by y bits

bitwise AND assignment &= x &= y x = x & y

bitwise OR assignment |= x |= y x = x | y

bitwise XOR assignment ^= x ^= y x = x ^ y

Page 72: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Masks❖ In computer science, a mask is data that is used for

bitwise operations, particularly in a bit field.

❖ Using a mask, multiple bits in a variable can be set either on, off or inverted from on to off (or vice versa) in a single bitwise operation.

Page 73: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Masking Bits to 1❖ To turn certain bits on, the bitwise OR operation can be

used, following the principle that Y OR 1 = 1 and Y OR 0 = Y.

❖ Therefore, to make sure a bit is on, OR can be used with a 1. To leave a bit unchanged, OR is used with a 0.

❖ Example: Masking “on” the higher bits (bits 4, 5, 6, 7), leaving the lower bits (bits 0, 1, 2, 3) unchanged.

1001 0101 1010 0101 OR 1111 0000 1111 0000 = 1111 0101 1111 0101

Page 74: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Masking Bits to 0❖ More often, in practice, bits that are to be ignored are "masked off" (or masked

to 0) rather than "masked on" (or masked to 1). There is no way to change a bit from on to off using the OR operation. Instead, bitwise AND is used.

❖ When a value is ANDed with a 1, the result is simply the original value, as in: Y AND 1 = Y. However, ANDing a value with 0 is guaranteed to return a 0, so it is possible to turn a bit off by ANDing it with 0: Y AND 0 = 0. To leave the other bits alone, ANDing them with a 1 can be done.

❖ Example: Masking “off” the higher bits (bits 4, 5, 6, 7), leaving the lower bits (bits 0, 1, 2, 3) unchanged.

1001 0101 1010 0101AND 0000 1111 0000 1111 = 0000 0101 0000 0101

Page 75: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Getter Exampleunsigned short x;

❖ Suppose x looks like this internally: 1011 0011 1100 1001

❖ Let’s partition x into k=4 partitions and attempt to get the value in partition 1 by masking “off” the other partitions…

1011 0011 1100 1001AND 0000 0000 1111 0000 = 0000 0000 1100 0000

❖ Now that the partition is isolated, we need to shift it to the right in order to produce the correct value:

0000 0000 1100 0000 >> 4

= 0000 0000 0000 1100 // 12

❖ The tricky part is constructing the mask and determining how far to shift.

unsigned short mask = ;x = x & mask;

x = x >> 4;

Page 76: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Setter Exampleunsigned short x;

❖ Suppose x looks like this internally: 1011 0011 1100 1001

❖ Let’s partition x into k=4 partitions and attempt to set the value in partition 2 to 9… First, let’s use a mask to zero out the partition.

1011 0011 1100 1001AND 1111 0000 1111 1111 = 1011 0000 1100 1001

❖ Now that the partition is zeroed out, we need to shift 9 to the left so that it aligns with our partition. 0000 0000 0000 1001 << 8

= 0000 1001 0000 0000 .

❖ Now we can OR it with our number: 1011 0000 1100 1001 OR 0000 1001 0000 0000 = 1011 1001 1100 1001

unsigned short mask = ;x = x & mask;

unsigned short y = 9; y = y << 8;

x = x | y;

Page 77: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Creating a Mask with all 0s or 1s

❖ unsigned int mask1 = 0u; // 00000000 00000000 00000000 00000000

❖ unsigned int mask1 = ~0u; // 11111111 11111111 11111111 11111111

Page 78: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Querying the Status of a Bit using a Mask❖ It is possible to use masks to easily check the state of individual bits regardless of the other bits.

❖ To do this, turning off all the other bits using the bitwise AND is done as discussed above and the value is compared with 0. If it is equal to 0, then the bit was off, but if the value is any other value, then the bit was on.

❖ NOTE: What makes this convenient is that it is not necessary to figure out what the value actually is, just that it is not 0.

❖ Example: Querying the status of the 4th bit 1011 0011 1100 1001 . 1011 0011 1100 1001 .AND 0000 0010 0000 0000 . AND 0000 1000 0000 0000 . = 0000 0010 0000 0000 // != 0 = 0000 0000 0000 0000 // == 0

The bit was on! The bit was off!

❖ You can construct this particular mask by left shifting 1. For example:

❖ To query bit 0, use mask = 1 << 0;

❖ To query bit 7 use mask = 1 << 7;

Page 79: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Masks for Options❖ Suppose we’ve defined a bunch of masks that represent the powers of 2:

const unsigned byte CHEESE = 1u << 0; // 0000 0001 const unsigned byte PEPPERONI = 1u << 1; // 0000 0010 const unsigned byte MUSHROOMS = 1u << 2; // 0000 0100 const unsigned byte BELL_PEPPERS = 1u << 3; // 0000 1000

❖ Also suppose that we have a function that expects a mask:void orderPizza(unsigned byte toppings);

❖ We might invoke the function as follows:orderPizza(CHEESE | PEPPERONI | MUSHROOMS);

❖ The inside of the function might look something like this:void orderPizza(unsigned byte toppings) { if ((toppings & CHEESE) != 0) addCheese(); if ((toppings & PEPPERONI) != 0) addPepperoni(); if ((toppings & MUSHROOMS) != 0) addMushrooms(); if ((roppings & BELL_PEPPERS) != 0) addBellPeppers(); } // orderPizza

0000 0001OR 0000 0010OR 0000 0100———————————— = 0000 0111

Page 80: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

What a surprise!

Quiz!?

Page 81: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Meeting TimesThis Week’s Readings DEITEL 6.6, 6.10–6.21 DEITEL 8.1–8.12

Next Week’s ReadingsDEITEL 3, 9, & 10 APUE 3.1--3.17

Page 82: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

@TODO❖ Nike username/password

❖ Problems? —> [email protected]

❖ Setup your Nike account —> According to Lab 01

—————————

❖ Go over quiz 1!

Page 83: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Declaration of Variables❖ C++ is a strongly-typed language, and requires every variable to be

declared with its type before its first use.

❖ This informs the compiler the size to reserve in memory for the variable and how to interpret its value.

❖ The syntax to declare a new variable in C++ is straightforward: we simply write the type followed by the variable name (i.e., its identifier).

❖ For example:int a;float mynumber;

Page 84: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Declaration of Variables❖ If declaring more than one variable of the same type, they

can all be declared in a single statement by separating their identifiers with commas.

❖ For example:int a, b, c;

❖ This declares three variables (a, b and c), all of them of type int.

Page 85: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Initialization of Variables❖ In C++, there are three ways to initialize variables.

❖ C-like Initialization: consists of appending an equal sign followed by the value to which the variable is initialized.

type identifier = initial_value;int x = 0;

❖ Constructor Initialization: encloses the initial value between parentheses.type identifier (initial_value);int x (0);

❖ Uniform Initialization (C++11): encloses the initial value between curly braces.type identifier {initial_value};int x {0};

Page 86: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Type Inference and Deduction❖ When a new variable is initialized, the compiler can figure out what the

type of the variable is automatically by the initializer value.

❖ For this, it suffices to use auto as the type specifier for the variable: int foo = 0;auto bar = foo; // the same as: int bar = foo;

❖ Variables that are not initialized can also make use of type deduction with the decltype specifier: int foo = 0;decltype(foo) bar; // the same as: int bar;

Page 87: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Type Inference and Deduction❖ auto and decltype are powerful features recently added

to the language.

❖ But the type deduction features they introduce are meant to be used either when the type cannot be obtained by other means or when using it improves code readability.

❖ The two examples on the previous slide were likely neither of these use cases. In fact they probably decreased readability, since, when reading the code, one has to search for the type of foo to actually know the type of bar.

Page 88: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Standard Strings

❖ Fundamental types represent the most basic types handled by the machines where the code may run.

❖ But one of the major strengths of the C++ language is its rich set of compound types, of which the fundamental types are mere building blocks.

❖ An example of compound type is the string class. Variables of this type are able to store sequences of characters, such as words or sentences.

Page 89: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Standard Strings❖ A first difference with fundamental data types is that in order to declare and

use objects (variables) of this type, the program needs to include the header where the type is defined within the standard library (header <string>): #include <iostream>#include <string>#include <cstdlib>int main() { std::string str; str = “my string”; std::cout << str << std::endl; return EXIT_SUCCESS;} // main

Page 90: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Constants and Literals❖ Constants are expressions with a fixed value.

❖ Literals are the most obvious kind of constants. They are used to express particular values within the source code of a program.

❖ For example:int a = 5;

❖ The 5 in the example above is a literal constant.

❖ Literal constants can be classified into: integer, floating-point, characters, strings, Boolean, pointers, and user-defined literals.

Page 91: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Integer Literals❖ These are numerical constants that identify integer values. 1776707-273

❖ Notice that they are not enclosed in quotes or any other special character; they are a simple succession of digits representing a whole number in decimal base.

❖ For example, 1776 always represents the value one thousand seven hundred seventy-six.

Page 92: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Integer Literals❖ In addition to decimal numbers (those that most of us use every day), C++ allows

the use of octal numbers (base 8), hexadecimal numbers (base 16), and binary numbers (base 2) as literal constants.

❖ For octal literals, the digits are preceded with a 0 (zero) character. And for hexadecimal, they are preceded by the characters 0x (zero, x).

❖ For example, the following literal constants are all equivalent to each other: 75 // decimal0113 // octal0x4b // hex0b1001011 // binary (C++14)

❖ All of these represent the same number: 75 (seventy-five) expressed as a base-10 numeral, octal numeral and hexadecimal numeral, respectively.

Page 93: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Integer Literal Types

❖ Literal constants have a type, just like variables.

❖ By default, integer literals are of type int. However, certain suffixes may be appended to an integer literal to specify a different integer type:

Page 94: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Integer Literal Types❖ Unsigned may be combined with any of the other two in any

order to form unsigned long or unsigned long long.75 // int75u // unsigned int75l // long75ul // unsigned long75lu // unsigned long

❖ In all the cases above, the suffix can be specified using either upper or lowercase letters.

Page 95: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Floating Point Literals❖ They express real values, with decimals and/or exponents.

❖ They can include either a decimal point, an e character (that expresses “times 10 raised to the Xth power", where X is an integer value that follows the e character), or both a decimal point and an e character: 3.14159 // 3.141596.02e23 // 6.02 x 10^231.6e-19 // 1.6 x 10^-193.0 // 3.0

Page 96: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Floating Point Literal Types❖ The default type for floating-point literals is double.

❖ Floating-point literals of type float or long double can be specified by adding one of the following suffixes:

❖ Examples: 3.14159L // long double6.02e23f // float

❖ Any of the letters that can be part of a floating-point numerical constant (e, f, l) can be written using either lower or uppercase letters with no difference in meaning.

Page 97: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Character and String Literals❖ Character and string literals are enclosed in quotes: 'z''p'"Hello world""How do you do?"

❖ The first two expressions represent single-character literals, and the following two represent string literals composed of several characters.

❖ Notice that to represent a single character, we enclose it between single quotes ('), and to express a string (which generally consists of more than one character), we enclose the characters between double quotes (").

Page 98: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Character and String Literals❖ Both single-character and string literals require quotation marks

surrounding them to distinguish them from possible variable identifiers or reserved keywords.

❖ Notice the difference between these two expressions: x'x'

❖ Here, x alone would refer to an identifier, such as the name of a variable or a compound type, whereas 'x' (enclosed within single quotation marks) would refer to the character literal 'x' (the character that represents a lowercase x letter).

Page 99: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Special Characters❖ Character and string literals can also represent special

characters that are difficult or impossible to express otherwise in the source code of a program, like newline (\n) or tab (\t).

❖ These special characters are all of them preceded by a backslash character (\).

Page 100: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Other Literals❖ Three keyword literals exist in C++: true, false and nullptr:

❖ true and false are the two possible values for variables of type bool.

❖ nullptr is the null pointer value.

❖ Examples: bool foo = true;bool var = false;int * p = nullptr; // more on this later

Page 101: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Type Constant Expressions

❖ Sometimes, it is just convenient to give a name to a constant value: const double PI = 3.1415926;const char TAB = '\t';

❖ This is similar to using the final keyword in Java.

Page 102: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Preprocessor Definitions❖ Another mechanism to name constant values is the use of

preprocessor definitions. They have the following form:#define identifier replacement

❖ After this directive, any occurrence of identifier in the code is interpreted as replacement, where replacement is any sequence of characters (until the end of the line).

❖ This replacement is performed by the preprocessor, and happens before the program is compiled, thus causing a sort of blind replacement: the validity of the types or syntax involved is not checked in any way.

Page 103: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Preprocessor Definitions❖ Example #include <iostream>#include <cstdlib>#define PI 3.14159int main() { double radius = 5.0; double area = 2 * PI * radius; std::cout << area << std::endl; return EXIT_SUCCESS;} // main

❖ Note that the #define lines are preprocessor directives, and as such are single-line instructions that -unlike C++ statements- do not require semicolons (;) at the end; the directive extends automatically until the end of the line.

❖ If a semicolon is included in the line, it is part of the replacement sequence and is also included in all replaced occurrences

Page 104: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Assignment Operator❖ The assignment operator assigns a value to a variable.x = 5;

❖ This statement assigns the integer value 5 to the variable x.

❖ The assignment operation always takes place from right to left, and never the other way around:x = y;

❖ This statement assigns to variable x the value contained in variable y. The value of x at the moment this statement is executed is lost and replaced by the value of y.

Page 105: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Arithmetic Operators and Compound Assignment

❖ The five arithmetical operations supported by C++ are:

❖ Compound assignment operators modify the current value of a variable by performing an operation on it. They are equivalent to assigning the result of an operation to the first operand:

Page 106: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Increment and Decrement Operators❖ A peculiarity of this operator is that it can be used both as a prefix and as a suffix. That

means that it can be written either before the variable name (++x) or after it (x++).

❖ Although in simple expressions like x++ or ++x, both have exactly the same meaning; in other expressions in which the result of the increment or decrement operation is evaluated, they may have an important difference in their meaning:

❖ In the case that the increment operator is used as a prefix (++x) the value, the expression evaluates to the final value of x, once it is already increased. On the other hand, in case that it is used as a suffix (x++) the value stored in x the expression evaluates to the value x had before being increased. Notice the difference:

Page 107: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Relational Operators❖ Two expressions can be compared using relational and equality operators. For

example, to know if two values are equal or if one is greater than the other.

❖ The result of such an operation is either true or false (i.e., a Boolean value).

❖ The relational operators in C++ are:

❖ Be careful! The assignment operator (operator =, with one equal sign) is not the same as the equality comparison operator (operator ==, with two equal signs)

Page 108: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Logical Operators❖ The operator ! is the C++ operator for the Boolean operation NOT. It

has only one operand, to its right, and inverts it, producing false if its operand is true, and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand.

❖ The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds to the Boolean logical operation AND, which yields true if both its operands are true, and false otherwise.

Page 109: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Short Circuit❖ When using the logical operators, C++ only evaluates what is necessary from left to right to come up

with the combined relational result, ignoring the rest. This is known as short-circuit evaluation, and works like this for these operators:

❖ Logical AND: if the left-hand side expression is false, the combined result is false (the right-hand side expression is never evaluated).

❖ Logical OR: if the left-hand side expression is true, the combined result is true (the right-hand side expression is never evaluated).

❖ This is mostly important when the right-hand expression has side effects, such as altering values: if ( (i<10) && (++i<n) ) { /*...*/ } // note that the condition increments i

❖ Here, the combined conditional expression would increase i by one, but only if the condition on the left of && is true, because otherwise, the condition on the right-hand side (++i<n) is never evaluated.

Page 110: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Ternary Operator❖ The conditional operator evaluates an expression, returning one value if that

expression evaluates to true, and a different one if the expression evaluates as false. Its syntax is:condition ? result1 : result2

❖ If condition is true, the entire expression evaluates to result1, and otherwise to result2.

❖ Examples: 7==5 ? 4 : 3 // evaluates to 3, since 7 is not equal to 5. 7==5+2 ? 4 : 3 // evaluates to 4, since 7 is equal to 5+2. 5>3 ? a : b // evaluates to the value of a, // since 5 is greater than 3. a>b ? a : b // evaluates to whichever is greater, a or b.

Page 111: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Comma Separator❖ The comma operator (,) is used to separate two or more expressions

that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the right-most expression is considered.

❖ For example, the following code:a = (b=3, b+2);

❖ would first assign the value 3 to b, and then assign b+2 to variable a.

❖ So, at the end, variable a would contain the value 5 while variable b would contain value 3.

Page 112: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Explicit Casting Operator❖ Type casting operators allow to convert a value of a given type to another type. There

are several ways to do this in C++. The simplest one, which has been inherited from the C language, is to precede the expression to be converted by the new type enclosed between parentheses (()): int i;float f = 3.14;i = (int) f;

❖ The previous code converts the floating-point number 3.14 to an integer value (3); the remainder is lost. Here, the typecasting operator was (int). Another way to do the same thing in C++ is to use the functional notation preceding the expression to be converted by the type and enclosing the expression between parentheses: i = int (f);

❖ Both ways of casting types are valid in C++.

Page 113: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Basic I/O❖ C++ uses a convenient abstraction called streams to perform input and output operations in

sequential media such as the screen, the keyboard or a file.

❖ A stream is an entity where a program can either insert or extract characters to/from. There is no need to know details about the media associated to the stream or any of its internal specifications. All we need to know is that streams are a source/destination of characters, and that these characters are provided/accepted sequentially (i.e., one after another).

❖ The standard library (in <iostream>) defines a handful of stream objects that can be used to access what are considered the standard sources and destinations of characters by the environment where the program runs:

Page 114: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Standard Output❖ On most program environments, the standard output by default is the screen, and

the C++ stream object defined to access it is cout.

❖ For formatted output operations, cout is used together with the insertion operator, which is written as << (i.e., two "less than" signs). cout << "Output sentence"; // prints Output sentence on screen cout << 120; // prints number 120 on screen cout << x; // prints the value of x on screen

❖ The << operator inserts the data that follows it into the stream that precedes it. In the examples above, it inserted the literal string Output sentence, the number 120, and the value of variable x into the standard output stream cout. Notice that the sentence in the first statement is enclosed in double quotes (") because it is a string literal, while in the last one, x is not.

Page 115: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Standard Output❖ Multiple insertion operations (<<) may be chained in a single statement: cout << "This " << " is a " << "single C++ statement";

❖ This last statement would print the text This is a single C++ statement. Chaining insertions is especially useful to mix literals and variables in a single statement: cout << "I am " << age << " years old and my zipcode is " << zipcode;

❖ Assuming the age variable contains the value 24 and the zipcode variable contains 90064, the output of the previous statement would be: I am 24 years old and my zipcode is 90064

Page 116: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Standard Output❖ What cout does NOT do automatically is add line breaks at the end, unless

instructed to do so. For example, take the following two statements inserting into cout:cout << "This is a sentence.";cout << "This is another sentence.";

❖ The output would be in a single line, without any line breaks in between. Something like: This is a sentence.This is another sentence.

❖ To insert a line break, a new-line character shall be inserted at the exact position the line should be broken. In C++, a new-line character can be specified as \n. Alternatively, the std::endl manipulator can also be used to break lines.

Page 117: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Standard Input❖ In most program environments, the standard input by default is the keyboard,

and the C++ stream object defined to access it is cin.

❖ For formatted input operations, cin is used together with the extraction operator, which is written as >> (i.e., two "greater than" signs). This operator is then followed by the variable where the extracted data is stored. For example: int age;cin >> age;

❖ The first statement declares a variable of type int called age, and the second extracts from cin a value to be stored in it. This operation makes the program wait for input from cin; generally, this means that the program will wait for the user to enter some sequence with the keyboard.

Page 118: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Chaining cin❖ Extractions on cin can also be chained to request more

than one datum in a single statement: cin >> a >> b;

❖ This is equivalent to: cin >> a;cin >> b;

Page 119: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Be Careful❖ What happens if the user enters something else that

cannot be interpreted as target variable’s type?

❖ The extraction operation fails.

❖ By default, the program continue without setting a value for the target variable, producing undetermined results if the value of the variable is used later.

❖ Later we will see how stringstreams can be used to have better control over user input.

Page 120: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

cin and Strings❖ The extraction operator can be used on cin to get strings of

characters in the same way as with fundamental data types: string mystring;cin >> mystring;

❖ However, cin extraction always considers spaces (whitespaces, tabs, new-line...) as terminating the value being extracted, and thus extracting a string means to always extract a single word, not a phrase or an entire sentence.

Page 121: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

getline❖ To get an entire line from cin, there exists a function, called getline, that

takes the stream (cin) as first argument, and the string variable as second. For example: string name;cout << “What’s your name? “;getline(cin, name);cout << “Hello “ << name << endl;

❖ The standard behavior that most users expect from a console program is that each time the program queries the user for input, the user introduces the field, and then presses ENTER (or RETURN).

❖ Therefore, unless you have a strong reason not to, you should always use getline to get input in your console programs instead of extracting from cin.

Page 122: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

stringstream

❖ The standard header <sstream> defines a type called stringstream that allows a string to be treated as a stream, and thus allowing extraction or insertion operations from/to strings in the same way as they are performed on cin and cout.

❖ This feature is most useful to convert strings to numerical values and vice versa.

❖ For example, in order to extract an integer from a string we can write: string str = “1204”;int n;stringstream(str) >> n;cout << “the number times 2 is ” << (n * 2) << endl;

❖ Later, we’ll examine how to use exceptions to check the state of the stringstream.

Page 123: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Statements and Flow Control❖ Many of the flow control statements require a generic (sub)statement as part of

its syntax.

❖ This statement may either be a simple C++ statement, -such as a single instruction, terminated with a semicolon (;) - or a compound statement.

❖ A compound statement is a group of statements (each of them terminated by its own semicolon), but all grouped together in a block, enclosed in curly braces: {}: { statement1; statement2; statement3; }

❖ The entire block is considered a single statement (composed itself of multiple sub-statements). Whenever a generic statement is part of the syntax of a flow control statement, this can either be a simple statement or a compound statement.

Page 124: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

if and else❖ The if keyword is used to execute a statement or block, if, and only if, a

condition is fulfilled. Its syntax is: if (condition) statement

❖ Here, condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is not executed (it is simply ignored), and the program continues right after the entire selection statement.

❖ if statements can also specify what happens when the condition is not fulfilled, by using the else keyword to introduce an alternative statement. Its syntax is: if (condition) statement1 else statement2

Page 125: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

if, else, and else ifif (x == 100) { cout << “x is ”; cout << x << endl;} // ifif (x == 100) { cout << “x is 100” << endl;} else { cout << “x is not 100” << endl;} // ifif (x > 0) { cout << “x is positive” << endl;} else if (x < 0) { cout << “x is negative” << endl;} else { cout << “x is zero” << endl;} // if

Page 126: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

while loop❖ The simplest kind of loop is the while-loop. Its syntax is: while (expression) statement;

❖ The while-loop simply repeats statement while expression is true.

❖ If, after any execution of statement, expression is no longer true, the loop ends, and the program continues right after the loop. int n = 10;while (n > 0) { cout << n << “, “; --n;} // whilecout << “liftoff!” << endl;

Page 127: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

do-while loop❖ A very similar loop is the do-while loop, whose syntax is: do statement while (condition);

❖ It behaves like a while-loop, except that condition is evaluated after the execution of statement instead of before, guaranteeing at least one execution of statement, even if condition is never fulfilled. string str;do { cout << “enter text: “; getline(cin, str); cout << “you entered: “ << str << endl; } while (str != “goodbye”);

❖ The do-while loop is usually preferred over a while-loop when the statement needs to be executed at least once, such as when the condition that is checked to end of the loop is determined within the loop statement itself.

Page 128: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

for loop❖ The for loop is designed to iterate a number of times. Its syntax is: for (initialization; condition; increase) statement

❖ Like the while-loop, this loop repeats statement while condition is true. But, in addition, the for loop provides specific locations to contain an initialization and an increase expression, executed before the loop begins the first time, and after each iteration, respectively. Therefore, it is especially useful to use counter variables as condition.for (int n = 10; n > 0; n--) { cout << n << “, “;} // forcout << “liftoff!” << endl;

Page 129: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

for loop❖ The three fields in a for-loop are optional. They can be left empty,

but in all cases the semicolon signs between them are required.

❖ For example, for (;n<10;) is a loop without initialization or increase (equivalent to a while-loop);

❖ and for (;n<10;++n) is a loop with increase, but no initialization (maybe because the variable was already initialized before the loop).

❖ A for loop with no condition is equivalent to a loop with true as condition (i.e., an infinite loop).

Page 130: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

for loop❖ Because each of the fields is executed in a particular time in the life cycle of a loop, it may be

useful to execute more than a single expression as any of initialization, condition, or increase parts.

❖ Unfortunately, these are not statements, but rather, simple expressions, and thus cannot be replaced by a block. As expressions, they can, however, make use of the comma operator (,).

❖ This operator is an expression separator, and can separate multiple expressions where only one is generally expected. For example, using it, it would be possible for a for loop to handle two counter variables, initializing and increasing both: for (n = 0, i = 100; n != i; ++n, --i) { // whatever} // for

❖ This loop will execute 50 times if neither n or i are modified within the loop. n starts with a value of 0, and i with 100, the condition is n!=i (i.e., that n is not equal to i). Because n is increased by one, and i decreased by one on each iteration, the loop's condition will become false after the 50th iteration, when both n and i are equal to 50.

Page 131: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Range-based for loop❖ The for-loop has another syntax (sometimes referred to as a for comprehension or for-each loop),

which is used exclusively with ranges: for (declaration : range) statement;

❖ This kind of for loop iterates over all the elements in range, where declaration declares some variable able to take the value of an element in this range.

❖ Ranges are sequences of elements, including arrays, containers, and any other type supporting the functions begin and end (more on that later). string str = “hello”;for (char c : str) cout << “[“ << c << “]”;cout << endl;

❖ Range based loops usually make also use of type deduction for the type of the elements with auto. Typically, the range-based loop above can also be written as: for (auto c : str) cout << “[“ << c << “]”;

Page 132: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

break❖ break leaves a loop, even if the condition for its end is not fulfilled.

❖ It can be used to end an infinite loop, or to force it to end before its natural end.

❖ For example, let's stop the countdown before its natural end: for (int n = 10; n > 0; n--) { cout << n << “, “; if (n == 3) { cout << “aborted!” << endl; break; } // if} // for

Page 133: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

continue❖ The continue statement causes the program to skip the rest

of the loop in the current iteration, as if the end of the statement block had been reached, causing it to jump to the start of the following iteration.

❖ For example, let's skip number 5 in our countdown: for (int n = 10; n > 0; n--) { if (n == 5) continue; cout << n << “, “;} // forcout << “liftoff!” << endl;

Page 134: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

goto❖ goto allows to make an absolute jump to another point in the

program.

❖ This unconditional jump ignores nesting levels, and does not cause any automatic stack unwinding.

❖ Therefore, it is a feature to use with care, and preferably within the same block of statements, especially in the presence of local variables.

❖ The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:).

Page 135: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

goto❖ goto is generally deemed a low-level feature, with no particular

use cases in modern higher-level programming paradigms generally used with C++.

❖ But, just as an example, here is a version of our countdown loop using goto:int n = 10;mylabel:cout << n << “, “;n--;if (n > 0) goto mylabel;cout << “liftoff!” << endl;

Page 136: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

switch❖ The syntax of the switch statement is a bit peculiar. Its purpose is to check for a value among a number of possible

constant expressions. It is something similar to concatenating if-else statements, but limited to constant expressions. Its most typical syntax is: switch (expression) { case constant1: group-of-statements-1; break; case constant2: group-of-statements-2; break; . . . default: default-group-of-statements} // switch

❖ Finally, if the value of expression did not match any of the previously specified constants (there may be any number of these), the program executes the statements included after the default: label, if it exists (since it is optional).

❖ It works in the following way: switch evaluates expression and checks if it is equivalent to constant1; if it is, it executes group-of-statements-1 until it finds the break statement. When it finds this break statement, the program jumps to the end of the entire switch statement (the closing brace).

❖ If expression was not equal to constant1, it is then checked against constant2. If it is equal to this, it executes group-of-statements-2 until a break is found, when it jumps to the end of the switch.

Page 137: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Functions❖ In C++, a function is a group of statements that is given a name, and which can be called from some point

of the program.

❖ The most common syntax to define a function is: type name (param1, param2, …) { statements }

❖ For example:int addition (int a, int b) { int r; r = a + b; return r;} // additionint main() { int z; z = addition(5, 3); cout << “result is “ << z << endl; return EXIT_SUCCESS;} // main

Let’s draw a memory map of what’s happening on the stack.

A memory map is just a diagram that shows the layout of our program’s memory at some

point in time.

We’ll draw this on the board.

Page 138: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exampleint addition (int a, int b) { int r; r = a + b; return r;} // additionint main() { int z; z = addition(5, 3); cout << “result is “ << z << endl; return EXIT_SUCCESS;} // main

Address STACK

100 int z [JUNK]

Page 139: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exampleint addition (int a, int b) { int r; r = a + b; return r;} // additionint main() { int z; z = addition(5, 3); cout << “result is “ << z << endl; return EXIT_SUCCESS;} // main

Address STACK

100 int z [JUNK]

104108112

int aint bint r

53

[JUNK]

Page 140: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exampleint addition (int a, int b) { int r; r = a + b; return r;} // additionint main() { int z; z = addition(5, 3); cout << “result is “ << z << endl; return EXIT_SUCCESS;} // main

Address STACK

100 int z [JUNK]

104108112

int aint bint r

538

Page 141: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exampleint addition (int a, int b) { int r; r = a + b; return r;} // additionint main() { int z; z = addition(5, 3); cout << “result is “ << z << endl; return EXIT_SUCCESS;} // main

Address STACK

100 int z [JUNK]

104108112

int aint bint r

538

Page 142: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exampleint addition (int a, int b) { int r; r = a + b; return r;} // additionint main() { int z; z = addition(5, 3); cout << “result is “ << z << endl; return EXIT_SUCCESS;} // main

Address STACK

100 int z 8

104108112

int aint bint r

538

Page 143: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exampleint addition (int a, int b) { int r; r = a + b; return r;} // additionint main() { int z; z = addition(5, 3); cout << “result is “ << z << endl; return EXIT_SUCCESS;} // main

Address STACK

100 int z 8

104108112

int aint bint r

538

Page 144: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exampleint addition (int a, int b) { int r; r = a + b; return r;} // additionint main() { int z; z = addition(5, 3); cout << “result is “ << z << endl; return EXIT_SUCCESS;} // main

// AFTER EXECUTION

Address STACK

100 int z 8

104108112

int aint bint r

538

Page 145: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

The Return Value of main❖ If the execution of main ends normally without encountering a return statement

the compiler assumes the function ends with an implicit return statement:return EXIT_SUCCESS;

❖ Note that this only applies to function main for historical reasons. All other functions with a return type shall end with a proper return statement that includes a return value, even if this is never used.

❖ When main returns zero (either implicitly or explicitly), it is interpreted by the environment as that the program ended successfully. Other values may be returned by main, and some environments give access to that value to the caller in some way, although this behavior is not required nor necessarily portable between platforms.

❖ Because the implicit return EXIT_SUCCESS; statement for main is a tricky exception, some authors consider it good practice to explicitly write the statement.

Page 146: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Return Value of main❖ The values for main that are guaranteed to be

interpreted in the same way on all platforms are:

Value Description0 The program was successful.

EXIT_SUCCESS The program was successfu. Defined in <cstdlib>.EXIT_FAILURE The program failed. Defined in <cstdlib>.

❖ In Bash, you can print the exit code of the last program that terminated using the following command:

$ echo $?

Page 147: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Pass by Value❖ In the functions seen earlier, arguments have always been passed by value. This means

that, when calling a function, what is passed to the function are the values of these arguments on the moment of the call, which are copied into the variables represented by the function parameters.

❖ For example, take:int x = 5, y = 3, z;z = addition(x, y);

❖ In this case, function addition is passed 5 and 3, which are copies of the values of x and y, respectively. These values (5 and 3) are used to initialize the variables set as parameters in the function's definition, but any modification of these variables within the function has no effect on the values of the variables x and y outside it, because x and y were themselves not passed to the function on the call, but only copies of their values at that moment.

Page 148: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Pass by Reference❖ In certain cases, though, it may be useful to access an external variable from within a function.

To do that, arguments can be passed by reference, instead of by value.

❖ For example, the function duplicate in this code duplicates the value of its three arguments, causing the variables used as arguments to actually be modified by the call: void duplicate (int & a, int & b, int & c) { a *= 2; b *= 2; c *= 2;} // duplicateint main() { int x = 1, y = 3, z = 7; duplicate(x, y, z); cout << "x=" << x << ", y=" << y << ", z=" << z; return EXIT_SUCCESS;} // main

Output: x=2, y=6, z=14

Page 149: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Pass by Reference❖ To gain access to its arguments, the function on the previous slide

declares its parameters as references.

❖ In C++, references are indicated with an ampersand (&) following the parameter type, as in the parameters taken by duplicate in the previous slide.

❖ When a variable is passed by reference, what is passed is no longer a copy, but the variable itself, the variable identified by the function parameter, becomes somehow associated with the argument passed to the function, and any modification on their corresponding local variables within the function are reflected in the variables passed as arguments in the call.

Page 150: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Pass by Reference

❖ In fact, a, b, and c become aliases of the arguments passed on the function call (x, y, and z) and any change on a within the function is actually modifying variable x outside the function.

❖ Any change on b modifies y, and any change on c modifies z.

❖ That is why when, in the example, function duplicate modifies the values of variables a, b, and c, the values of x, y, and z are affected.

Page 151: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems ProgrammingNoyes, Katherine. “Linux’s Brilliant 25-Year History, in Pictures.” PCWorld. IDG Consumer & SMB, 25 Aug. 2016. Web.

Page 152: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Meeting TimesThis Week’s Readings DEITEL 6.6, 6.10–6.21 DEITEL 8.1–8.12

Next Week’s ReadingsDEITEL 3, 9, & 10 APUE 3.1--3.17

Page 153: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Functions❖ In C++, a function is a group of statements that is given a name, and which can be called from some point

of the program.

❖ The most common syntax to define a function is: type name (param1, param2, …) { statements }

❖ For example:int addition (int a, int b) { int r; r = a + b; return r;} // additionint main() { int z; z = addition(5, 3); cout << “result is “ << z << endl; return EXIT_SUCCESS;} // main

Let’s draw a memory map of what’s happening on the stack.

A memory map is just a diagram that shows the layout of our program’s memory at some

point in time.

We’ll draw this on the board.

Page 154: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exampleint addition (int a, int b) { int r; r = a + b; return r;} // additionint main() { int z; z = addition(5, 3); cout << “result is “ << z << endl; return EXIT_SUCCESS;} // main

Address STACK

100 int z [JUNK]

Page 155: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exampleint addition (int a, int b) { int r; r = a + b; return r;} // additionint main() { int z; z = addition(5, 3); cout << “result is “ << z << endl; return EXIT_SUCCESS;} // main

Address STACK

100 int z [JUNK]

104108112

int aint bint r

53

[JUNK]

Page 156: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exampleint addition (int a, int b) { int r; r = a + b; return r;} // additionint main() { int z; z = addition(5, 3); cout << “result is “ << z << endl; return EXIT_SUCCESS;} // main

Address STACK

100 int z [JUNK]

104108112

int aint bint r

538

Page 157: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exampleint addition (int a, int b) { int r; r = a + b; return r;} // additionint main() { int z; z = addition(5, 3); cout << “result is “ << z << endl; return EXIT_SUCCESS;} // main

Address STACK

100 int z [JUNK]

104108112

int aint bint r

538

Page 158: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exampleint addition (int a, int b) { int r; r = a + b; return r;} // additionint main() { int z; z = addition(5, 3); cout << “result is “ << z << endl; return EXIT_SUCCESS;} // main

Address STACK

100 int z 8

104108112

int aint bint r

538

Page 159: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exampleint addition (int a, int b) { int r; r = a + b; return r;} // additionint main() { int z; z = addition(5, 3); cout << “result is “ << z << endl; return EXIT_SUCCESS;} // main

Address STACK

100 int z 8

104108112

int aint bint r

538

Page 160: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exampleint addition (int a, int b) { int r; r = a + b; return r;} // additionint main() { int z; z = addition(5, 3); cout << “result is “ << z << endl; return EXIT_SUCCESS;} // main

// AFTER EXECUTION

Address STACK

100 int z 8

104108112

int aint bint r

538

Page 161: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

The Return Value of main❖ If the execution of main ends normally without encountering a return statement

the compiler assumes the function ends with an implicit return statement:return EXIT_SUCCESS;

❖ Note that this only applies to function main for historical reasons. All other functions with a return type shall end with a proper return statement that includes a return value, even if this is never used.

❖ When main returns zero (either implicitly or explicitly), it is interpreted by the environment as that the program ended successfully. Other values may be returned by main, and some environments give access to that value to the caller in some way, although this behavior is not required nor necessarily portable between platforms.

❖ Because the implicit return EXIT_SUCCESS; statement for main is a tricky exception, some authors consider it good practice to explicitly write the statement.

Page 162: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Return Value of main❖ The values for main that are guaranteed to be

interpreted in the same way on all platforms are:

Value Description0 The program was successful.

EXIT_SUCCESS The program was successfu. Defined in <cstdlib>.EXIT_FAILURE The program failed. Defined in <cstdlib>.

❖ In Bash, you can print the exit code of the last program that terminated using the following command:

$ echo $?

Page 163: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Pass by Value❖ In the functions seen earlier, arguments have always been passed by value. This means

that, when calling a function, what is passed to the function are the values of these arguments on the moment of the call, which are copied into the variables represented by the function parameters.

❖ For example, take:int x = 5, y = 3, z;z = addition(x, y);

❖ In this case, function addition is passed 5 and 3, which are copies of the values of x and y, respectively. These values (5 and 3) are used to initialize the variables set as parameters in the function's definition, but any modification of these variables within the function has no effect on the values of the variables x and y outside it, because x and y were themselves not passed to the function on the call, but only copies of their values at that moment.

Page 164: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Pass by Reference❖ In certain cases, though, it may be useful to access an external variable from within a function.

To do that, arguments can be passed by reference, instead of by value.

❖ For example, the function duplicate in this code duplicates the value of its three arguments, causing the variables used as arguments to actually be modified by the call: void duplicate (int & a, int & b, int & c) { a *= 2; b *= 2; c *= 2;} // duplicateint main() { int x = 1, y = 3, z = 7; duplicate(x, y, z); cout << "x=" << x << ", y=" << y << ", z=" << z; return EXIT_SUCCESS;} // main

Output: x=2, y=6, z=14

Page 165: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Pass by Reference❖ To gain access to its arguments, the function on the previous slide

declares its parameters as references.

❖ In C++, references are indicated with an ampersand (&) following the parameter type, as in the parameters taken by duplicate in the previous slide.

❖ When a variable is passed by reference, what is passed is no longer a copy, but the variable itself, the variable identified by the function parameter, becomes somehow associated with the argument passed to the function, and any modification on their corresponding local variables within the function are reflected in the variables passed as arguments in the call.

Page 166: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Pass by Reference

❖ In fact, a, b, and c become aliases of the arguments passed on the function call (x, y, and z) and any change on a within the function is actually modifying variable x outside the function.

❖ Any change on b modifies y, and any change on c modifies z.

❖ That is why when, in the example, function duplicate modifies the values of variables a, b, and c, the values of x, y, and z are affected.

Page 167: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Reminders❖ Project 1 is due MON 2016-09-12 @ 11:55 PM. 

❖ Description is posted on eLC.

Page 168: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Efficiency Considerations❖ Calling a function with parameters taken by value causes copies of the values to be

made. This is a relatively inexpensive operation for fundamental types such as int, but if the parameter is of a large compound type, it may result on certain overhead.

❖ For example, consider the following function: string concat(string a, string b) { return a + b;} // concat

❖ This function takes two strings as parameters (by value), and returns the result of concatenating them. By passing the arguments by value, the function forces a and b to be copies of the arguments passed to the function when it is called. And if these are long strings, it may mean copying large quantities of data just for the function call.

Page 169: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Efficiency Considerations❖ The copying that occurs on the previous slide can be avoided altogether if

both parameters are made references:string concat(string & a, string & b) { return a + b;} // concat

❖ Arguments by reference do not require a copy. The function operates directly on (aliases of) the strings passed as arguments, and, at most, it might mean the transfer of certain pointers to the function.

❖ In this regard, the version of concat taking references is more efficient than the version taking values, since it does not need to copy expensive-to-copy strings.

Page 170: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

const References❖ On the flip side, functions with reference parameters are generally perceived as

functions that modify the arguments passed, because that is what reference parameters are actually for.

❖ The solution is for the function to guarantee that its reference parameters are not going to be modified by this function.

❖ This can be done by qualifying the parameters as constant: string concat(const string & a, const string & b) { return a + b;} // concat

❖ By qualifying them as const, the function is forbidden to modify the values of neither a nor b, but can actually access their values as references (aliases of the arguments), without having to make actual copies of the strings.

Page 171: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

const References

❖ const references provide functionality similar to passing arguments by value, but with an increased efficiency for parameters of large types.

❖ That is why they are extremely popular in C++ for arguments of compound types.

❖ Note though, that for most fundamental types, there is no noticeable difference in efficiency, and in some cases, const references may even be less efficient!

Page 172: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Inline Functions❖ Calling a function generally causes a certain overhead (stacking arguments, jumps, etc...), and

thus for very short functions, it may be more efficient to simply insert the code of the function where it is called, instead of performing the process of formally calling a function.

❖ Preceding a function declaration with the inline specifier informs the compiler that inline expansion is preferred over the usual function call mechanism for a specific function.

❖ This does not change at all the behavior of a function, but is merely used to suggest the compiler that the code generated by the function body shall be inserted at each point the function is called, instead of being invoked with a regular function call. inline string concat(const string & a, const string & b) { return a + b;} // concat

❖ This informs the compiler that when concat is called, the program prefers the function to be expanded inline, instead of performing a regular call. inline is only specified in the function declaration, not when it is called.

Page 173: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Compiler Optimizations❖ Note that most compilers already optimize code to generate

inline functions when they see an opportunity to improve efficiency, even if not explicitly marked with the inline specifier.

❖ Therefore, the inline specifier merely indicates the compiler that inline is preferred for this function, although the compiler is free to not inline it, and optimize otherwise.

❖ In C++, optimization is a task delegated to the compiler, which is free to generate any code as long as the resulting behavior is the one specified by the code.

Page 174: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Overloaded Functions❖ In C++, two different functions can have the same name if their parameters are different; either

because they have a different number of parameters, or because any of their parameters are of a different type. int operate(int a, int b) { return a * b;} // operatedouble operate(double a, double b) { return a / b;} // operate

❖ The compiler knows which one to call in each case by examining the types passed as arguments when the function is called. If it is called with two int arguments, it calls to the function that has two int parameters, and if it is called with two doubles, it calls the one with two doubles.

❖ Note that a function cannot be overloaded only by its return type. At least one of its parameters must have a different type.

Page 175: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Overloaded Functions❖ On the previous slide, both functions have quite different

behaviors, the int version multiplies its arguments, while the double version divides them.

❖ This is generally not a good idea.

❖ Two functions with the same name are generally expected to have -at least- a similar behavior, but this example demonstrates that is entirely possible for them not to.

❖ Two overloaded functions (i.e., two functions with the same name) have entirely different definitions; they are, for all purposes, different functions, that only happen to have the same name.

Page 176: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Default Values in Function Parameters❖ In C++, functions can also have optional parameters, for which no arguments are required in

the call, in such a way that, for example, a function with three parameters may be called with only two.

❖ For this, the function shall include a default value for its last parameter, which is used by the function when called with fewer arguments. int divide(int a, int b = 2) { int r; r = a / b; return r;} // divideint main() { cout << divide(12) << endl; cout << divide(20, 4) << endl; return EXIT_SUCCESS;} // main

In this example, there are two calls to function divide. In the first one, divide(12), the call only passes one argument to the function, even though the function has two parameters.

In this case, the function assumes the second parameter to be 2 (notice the function definition, which declares its second parameter as int b=2). Therefore, the result is 6.

Page 177: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Default Values in Function Parameters❖ In C++, functions can also have optional parameters, for which no arguments are required in

the call, in such a way that, for example, a function with three parameters may be called with only two.

❖ For this, the function shall include a default value for its last parameter, which is used by the function when called with fewer arguments. int divide(int a, int b = 2) { int r; r = a / b; return r;} // divideint main() { cout << divide(12) << endl; cout << divide(20, 4) << endl; return EXIT_SUCCESS;} // main

In the second one, divide(20, 4), the call passes two arguments to the function.

Therefore, the default value for b (int b=2) is ignored, and b takes the value passed as argument, that is 4, yielding a result of 5.

Page 178: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Declaring Functions❖ In C++, identifiers can only be used in expressions once they

have been declared.

❖ The same applies to functions. Functions cannot be called before they are declared. That is why, in all the previous examples of functions, the functions were always defined before the main function, which is the function from where the other functions were called.

❖ If main were defined before the other functions, this would break the rule that functions shall be declared before being used, and thus would not compile.

Page 179: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Prototypes❖ The prototype of a function can

be declared without actually defining the function completely, giving just enough details to allow the types involved in a function call to be known.

❖ Naturally, the function shall be defined somewhere else, like later in the code.

void odd (int x);void even (int x);int main() { int i; do { cout << "Please, enter number (0 to exit): "; cin >> i; odd (i); } while (i != 0); return EXIT_SUCCESS;} // mainvoid odd(int x) { if ((x % 2)!= 0) cout << "It is odd." << endl; else even (x);} // oddvoid even(int x) { if ((x % 2) == 0) cout << "It is even." << endl; else odd (x);} // even

Page 180: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Prototypes❖ Declaring functions before being

defined is not only useful to reorganize the order of functions within the code.

❖ In some cases, such as in this particular case, at least one of the declarations is required, because odd and even are mutually called; there is a call to even in odd and a call to odd in even. And, therefore, there is no way to structure the code so that odd is defined before even, and even before odd.

void odd (int x);void even (int x);int main() { int i; do { cout << "Please, enter number (0 to exit): "; cin >> i; odd (i); } while (i != 0); return EXIT_SUCCESS;} // mainvoid odd(int x) { if ((x % 2)!= 0) cout << "It is odd." << endl; else even (x);} // oddvoid even(int x) { if ((x % 2) == 0) cout << "It is even." << endl; else odd (x);} // even

Page 181: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Header Files❖ Code files (with a .cpp or .cc

extension) are not the only files commonly seen in programs. The other type of file is called a header file, sometimes known as an include file.

❖ Header files almost always have a .h extension. The purpose of a header file is to hold declarations (often function prototypes) for other files to use.

oddeven.h #ifndef ODDEVEN_H #define ODDEVEN_H void odd(int x); void even(int x); #endifmain.cpp #include <iostream> #include “oddeven.h” int main() { int i; do { cout << "Please, enter number (0 to exit): "; cin >> i; odd (i); } while (i != 0); return EXIT_SUCCESS; } // mainoddeven.cpp include <iostream> include “oddeven.h” void odd(int x) { if ((x % 2)!= 0) cout << "It is odd." << endl; else even (x); } // odd void even(int x) { if ((x % 2) == 0) cout << "It is even." << endl; else odd (x); } // even

In oddeven.h, we include:• header guard: a preprocessor

directive that prevents the header file from being recursively included during the preprocessor phase

• function prototypes: our forward definitions.

Page 182: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Header Files❖ Code files (with a .cpp or .cc

extension) are not the only files commonly seen in programs. The other type of file is called a header file, sometimes known as an include file.

❖ Header files almost always have a .h extension. The purpose of a header file is to hold declarations (often function prototypes) for other files to use.

oddeven.h #ifndef ODDEVEN_H #define ODDEVEN_H void odd(int x); void even(int x); #endifmain.cpp #include <iostream> #include “oddeven.h” int main() { int i; do { cout << "Please, enter number (0 to exit): "; cin >> i; odd (i); } while (i != 0); return EXIT_SUCCESS; } // mainoddeven.cpp include <iostream> include “oddeven.h” void odd(int x) { if ((x % 2)!= 0) cout << "It is odd." << endl; else even (x); } // odd void even(int x) { if ((x % 2) == 0) cout << "It is even." << endl; else odd (x); } // even

In main.cpp, we include:• an include for our header file: so

that we have the function prototypes needed for the file to compile

Page 183: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Header Files❖ Code files (with a .cpp or .cc

extension) are not the only files commonly seen in programs. The other type of file is called a header file, sometimes known as an include file.

❖ Header files almost always have a .h extension. The purpose of a header file is to hold declarations (often function prototypes) for other files to use.

oddeven.h #ifndef ODDEVEN_H #define ODDEVEN_H void odd(int x); void even(int x); #endifmain.cpp #include <iostream> #include “oddeven.h” int main() { int i; do { cout << "Please, enter number (0 to exit): "; cin >> i; odd (i); } while (i != 0); return EXIT_SUCCESS; } // mainoddeven.cpp include <iostream> include “oddeven.h” void odd(int x) { if ((x % 2)!= 0) cout << "It is odd." << endl; else even (x); } // odd void even(int x) { if ((x % 2) == 0) cout << "It is even." << endl; else odd (x); } // even

In oddeven.cpp, we include:• an include for out header file: so

that we have the function prototypes needed for the file to compile

• function definitions: for the prototypes declared in odd even.h

Page 184: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Compiling and Running the Example❖ You could just do: $ g++ -o example oddeven.cpp main.cpp$ ./example

❖ However, let’s illustrate that forward declarations in our header files are working properly by compiling each source file separately and then linking them together to form our executable: $ g++ -c -o main.o main.cpp$ g++ -c -o oddeven.o oddeven.cpp$ g++ -o example oddeven.o main.o$ ./example

Notice how we were able to compile main.cpp, even though we

had no implementation for the functions defined in oddeven.h.

Page 185: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Recursivity❖ Recursivity is the property that functions have to be called by themselves. It is useful for some

tasks, such as sorting elements, or calculating the factorial of numbers.

❖ For example, in order to obtain the factorial of a number (n!) the mathematical formula would be: n! = n * (n - 1)!

❖ And a recursive function to calculate this in C++ could be: long factorial(long a) { if (a > 1) { return a * factorial(a-1); } else { return 1; } // if} // factorial

❖ You do not necessarily need to include the function prototype for a recursive function before the function declaration, even though the function is calling itself.

Page 186: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Makefiles❖ Compiling your source code files can be tedious, specially when

you want to include several source files and have to type the compiling command every time you want to do it.

❖ Well, I have news for you... Your days of command line compiling are (mostly) over, because YOU will learn how to write Makefiles.

❖ Makefiles are special format files that together with the make utility will help you to automagically build and manage your projects.

❖ Before we look at compiling using a Makefile, let’s examine how to manually compile a small multi-file C++ project using GCC.

Page 187: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

main.cpp#include <iostream>#include <cstdlib> #include "functions.h" using std::cout;using std::endl;

int main() { print_hello(); cout << "The factorial of 5 is " << factorial(5) << endl; return EXIT_SUCCESS; } // main

Page 188: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

functions.h#ifndef FUNCTIONS_H#define FUNCTIONS_Hvoid print_hello(); int factorial(int n);#endif

Page 189: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

hello.cpp#include <iostream>#include "functions.h"using std::cout; using std::endl;

void print_hello(){ cout << "Hello World!" << endl;} // print_hello

Page 190: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

factorial.cpp#include "functions.h"

int factorial(int n){ if (n != 1) return n * factorial(n - 1); else return 1;} // factorial

Page 191: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Compiling Manually❖ You can preprocess, compile, and link all in one go: $ g++ -o hello main.cpp hello.cpp factorial.cpp $ ./hello

❖ You can also preprocess and compile each file separately, then link: $ g++ -c main.cpp$ g++ -c hello.cpp$ g++ -c factorial.cpp$ g++ -o hello main.o hello.o factorial.o$ ./hello

should be equivalent to $ g++ -c -o main.o main.cpp

Page 192: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Sample MakefileCC = g++ DEBUG = -g CFLAGS = -Wall -c $(DEBUG) LFLAGS = -Wall $(DEBUG)

hello: main.o hello.o factorial.o $(CC) $(LFLAGS) -o hello main.o hello.o factorial.o

main.o: main.cpp functions.h $(CC) $(CFLAGS) main.cpp

hello.o: hello.cpp functions.h $(CC) $(CFLAGS) hello.cpp

factorial.o: factorial.cpp functions.h $(CC) $(CFLAGS) factorial.cpp

run: hello ./hello

clean: rm -rf hello rm -rf *.o

Macro Variables: variables that are substituted in. They allow to easily

change compile and linking flags in a single place.

-g adds debugging information that

we’ll need if we want to use gdb.

-Wall turns on all warning flags in gcc.

Page 193: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Sample MakefileCC = g++ DEBUG = -g CFLAGS = -Wall -c $(DEBUG) LFLAGS = -Wall $(DEBUG)

hello: main.o hello.o factorial.o $(CC) $(LFLAGS) -o hello main.o hello.o factorial.o

main.o: main.cpp functions.h $(CC) $(CFLAGS) main.cpp

hello.o: hello.cpp functions.h $(CC) $(CFLAGS) hello.cpp

factorial.o: factorial.cpp functions.h $(CC) $(CFLAGS) factorial.cpp

run: hello ./hello

clean: rm -rf hello rm -rf *.o

Make Targets: usually represent files that you want built.

Dependencies: files or targets required in order to build a target.

Commands: commands that need to be run in order to build the target.

Page 194: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Sample MakefileCC = g++ DEBUG = -g CFLAGS = -Wall -c $(DEBUG) LFLAGS = -Wall $(DEBUG)

hello: main.o hello.o factorial.o $(CC) $(LFLAGS) -o hello main.o hello.o factorial.o

main.o: main.cpp functions.h $(CC) $(CFLAGS) main.cpp

hello.o: hello.cpp functions.h $(CC) $(CFLAGS) hello.cpp

factorial.o: factorial.cpp functions.h $(CC) $(CFLAGS) factorial.cpp

run: hello ./hello

clean: rm -rf hello rm -rf *.o

Take care: There can be more than one command after the dependency line, but all commands must immediately follow the dependency line, and the first character of each command line

must be a TAB.

The most common error in writing a makefile is failing to put a TAB at the beginning of commands. The second most common error is to put a TAB at the beginning of blank lines. The first error causes the commands not to run. The second causes the "make" utility to

complain that there is a "blank" command.

Page 195: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Using the Makefile❖ There are several ways to run make:

❖ $ make… will look for a makefile in the current directory and run the commands of the first target, assuming that it has to based on the dependencies.

❖ $ make -f <filename> … will look for a makefile with the name <filename> in the current directory and run the commands of the first target, assuming that it has to based on the dependencies.

❖ $ make <target>… will again look for a file called makefile (and if that's not there, it looks for Makefile) and locate the target. This does not have to be the first target. It will run the commands provided the dependencies are more recent than the target.

Page 196: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Function Templates❖ Overloaded functions may have the same definition but for

different types.

❖ In Java, we can use generics to refactor the functions into a single generic method.

❖ In C++, we can use function templates.❖ Defining a function template follows the same syntax than a regular

function, except that it is preceded by the template keyword and a series of template parameters enclosed in angle-brackets <>: template <template-parameters> function-declaration

Page 197: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Function Templates❖ The template parameters are a series of parameters separated by commas.

These parameters can be generic template types by specifying either the class or typename keyword followed by an identifier. This identifier can then be used in the function declaration as if it was a regular type. template <typename T>T sum(T a, T b) { return a+b;} // sumint main() { int n1 = sum<int>(1, 2); double n2 = sum<double>(2.0, 3.0); cout << n1 << “, “ << n2 << endl; } // main

It makes no difference whether the generic type is specified with keyword typename or keyword class in the template argument list (they are 100% synonyms in template declarations).

Page 198: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Non-Type Template Arguments❖ The template parameters can not only include types introduced by class or typename, but can also include

expressions of a particular type: template <typename T, int N>T fixed_multiply (T val) { return val * N;} // fixed_multiplyint main() { cout << fixed_multiply<int, 2>(10) << endl; cout << fixed_multiply<int, 3>(10) << endl; } // main

❖ The second argument of the fixed_multiply function template is of type int. It just looks like a regular function parameter, and can actually be used just like one.

❖ But there exists a major difference: the value of template parameters is determined on compile-time to generate a different instantiation of the function fixed_multiply, and thus the value of that argument is never passed during runtime.

❖ For that same reason, the second template argument needs to be a constant expression (it cannot be passed a variable).

Page 199: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Scopes❖ Named entities, such as variables, functions, and compound types need

to be declared before being used in C++. The point in the program where this declaration happens influences its visibility.

❖ An entity declared outside any block has global scope, meaning that its name is valid anywhere in the code. While an entity declared within a block, such as a function or a selective statement, has block scope, and is only visible within the specific block in which it is declared, but not outside it.

❖ Variables with block scope are known as local variables.

❖ Variables with block scope that are introduced as function parameters are known as automatic local variables.

Page 200: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Scopesint foo; // global variableint some_function() { int bar; // local variable bar = 0;} // some_functionint other_function() { foo = 1; // ok: foo is a global variable bar = 2; // wrong: bar is not visible from this function } // other_function

Page 201: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Scopes

❖ In each scope, a name can only represent one entity.

❖ For example, there cannot be two variables with the same name in the same scope: int some_function() { int x; x = 0; double x; // wrong: name already used in this scope x = 0.0;} // some_function

Page 202: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

01110001 0x7101110101 0x7501101001 0x6901111010 0x7a

Quiz!

Mark your answers on the quiz and the SCANTRON form.

Make sure to include your 9-digit UGA ID on the SCANTRON form.

Page 203: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Namespaces❖ Only one entity can exist with a particular name in a particular scope.

❖ This is seldom a problem for local names, since blocks tend to be relatively short, and names have particular purposes within them.

❖ But non-local names bring more possibilities for name collision, especially considering that libraries may declare many functions, types, and variables, neither of them local in nature, and some of them very generic.

❖ Namespaces allow to group named entities that otherwise would have global scope into narrower scopes, giving them namespace scope. This allows organizing the elements of programs into different logical scopes referred to by names.

❖ The syntax to declare a namespace is: namespace identifier { named entities} // identifier

Where identifier is any valid identifier and named_entities is the set of variables, types and functions that are included within the namespace.

Page 204: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Namespacesnamespace myNS { int a, b;} // myNS

❖ In this case, the variables a and b are normal variables declared within a namespace called myNS.

❖ These variables can be accessed from within their namespace normally, with their identifier (either a or b), but if accessed from outside the myNS namespace they have to be properly qualified with the scope operator ::.

❖ For example, to access the previous variables from outside myNS they should be qualified like: myNS::amyNS::b

❖ Namespaces are particularly useful to avoid name collisions.

Page 205: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Namespaces❖ Namespaces can be split.

❖ Two segments of a code can be declared in the same namespace: namespace foo { int a; }namespace bar { int b; }namespace foo { int c; }

❖ This declares three variables: a and c are in namespace foo, while b is in namespace bar.

❖ Namespaces can even extend across different translation units (i.e., across different files of source code).

Page 206: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Storage Classes❖ The storage for variables with global or namespace scope is

allocated for the entire duration of the program.

❖ This is known as static storage, and it contrasts with the storage for local variables (those declared within a block).

❖ Local variables use what is known as automatic storage.

❖ The storage for local variables is only available during the block in which they are declared; after that, that same storage may be used for a local variable of some other function, or used otherwise.

❖ This is because of how stack memory works.

Page 207: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Storage Classes❖ There is another substantial difference between variables with

static storage and variables with automatic storage:

❖ Variables with static storage (such as global variables) that are not explicitly initialized are automatically initialized to zeroes.

❖ Variables with automatic storage (such as local variables) that are not explicitly initialized are left uninitialized, and thus have an undetermined value.

❖ Note: Different compilers may actually initialize automatic variables, but the C++ specification does not guarantee such initialization.

Page 208: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Arrays❖ An array is a series of elements of the same type placed in contiguous

memory locations that can be individually referenced by adding an index to a unique identifier.

❖ For example, an array containing 5 integer values of type int called foo could be represented as:

❖ where each blank panel represents an element of the array. In this case, these are values of type int. These elements are numbered from 0 to 4, being 0 the first and 4 the last; In C++, the first element in an array is always numbered with a zero (not a one), no matter its length.

Page 209: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Arrays❖ Like a regular variable, an array must be declared before it is used.

❖ A typical declaration for an array in C++ is:type name [elements];

where type is a valid type (such as int, float...), name is a valid identifier and the elements field (which is always enclosed in square brackets []), specifies the length of the array in terms of the number of elements.

❖ Therefore, the foo array, with five elements of type int, can be declared as:int foo [5];

❖ NOTE: The elements field within square brackets [], representing the number of elements in the array, must be a constant expression, since arrays are blocks of static memory whose size must be determined at compile time, before the program runs. We’ll discuss how to use a variable expression for array lengths when we cover dynamic memory.

Page 210: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Initializing Arrays❖ By default, regular arrays of local scope (for example, those declared within a function) are left

uninitialized.

❖ This means that none of its elements are set to any particular value; their contents are undetermined at the point the array is declared.

❖ But the elements in an array can be explicitly initialized to specific values when it is declared, by enclosing those initial values in braces {}. int foo [5] = {16, 2, 77, 40, 12071};

❖ The number of values between braces {} shall not be greater than the number of elements in the array. For example, in the example above, foo was declared having 5 elements (as specified by the number enclosed in square brackets, []), and the braces {} contained exactly 5 values, one for each element.

Page 211: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Array Initialization❖ When an initialization of values is provided for an array, C++

allows the possibility of leaving the square brackets empty [].

❖ In this case, the compiler will assume automatically a size for the array that matches the number of values included between the braces {}:int foo [] = {16, 2, 77, 40, 12071};

❖ After this declaration, array foo would be 5 int long, since we have provided 5 initialization values.

Page 212: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Universal Array Initialization❖ the evolution of C++ has led to the adoption of universal initialization also

for arrays.

❖ Therefore, there is no longer need for the equal sign between the declaration and the initializer.

❖ Both these statements are equivalent: int foo[] = { 10, 20, 30 };int foo[] { 10, 20, 30 };

❖ Static arrays, and those declared directly in a namespace (outside any function), are always initialized. If no explicit initializer is specified, all the elements are default-initialized (with zeroes, for fundamental types).

Page 213: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Array Access❖ The values of any of the elements in an array can be accessed just like the value of a

regular value of the same type.

❖ Following the previous examples in which foo had 5 elements and each of those elements was of type int, the name which can be used to refer to each element is the following:

❖ For example, the following statement stores the value 75 in the third element of foo:foo [2] = 75;

❖ and, for example, the following copies the value of the third element of foo to a variable called x:

x = foo[2];

❖ Therefore, the expression foo[2] is itself a variable of type int.

Page 214: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Multidimensional Arrays

❖ Multidimensional arrays in C++ can be described as "arrays of arrays".

❖ From the programmer’s perspective, the behave the same way as in Java.

int jimmy [3][5]

char century [100][365][24]

Page 215: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Multidimensional Arrays❖ Multidimensional arrays are just an abstraction for

programmers, since the same results can be achieved with a simple array, by multiplying its indices: int jimmy [3][5]; // is equivalent toint jimmy [15]; // (3 * 5 = 15)

❖ With the only difference that with multidimensional arrays, the compiler automatically remembers the depth of each imaginary dimension.

Page 216: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Multidimensional Arrays❖ The following two pieces of code produce the exact

same result, but one uses a 2d array while the other uses a simple array:

Multidimensional Array Pseudo-Multidimensional Array#define WIDTH 5 #define HEIGHT 3

int jimmy [HEIGHT][WIDTH]; int n,m;

int main() { for (n = 0; n < HEIGHT; n++) { for (m = 0; m < WIDTH; m++) { jimmy[n][m]=(n+1)*(m+1); } // for } // for } // main

#define WIDTH 5 #define HEIGHT 3

int jimmy [HEIGHT * WIDTH]; int n,m;

int main() { for (n = 0; n < HEIGHT; n++) { for (m = 0; m < WIDTH; m++) { jimmy[n * WIDTH + m]=(n+1)*(m+1); } // for } // for } // main

Page 217: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Arrays as Parameters❖ At some point, we may need to pass an array to a function as a parameter.

❖ In C++, it is not possible to pass the entire block of memory represented by an array represents to a function directly as an argument.

❖ But what can be passed instead is its address. In practice, this has almost the same effect, and it is a much faster and more efficient operation.

❖ To accept an array as parameter for a function, the parameters can be declared as the array type, but with empty brackets, omitting the actual size of the array.

void foo(int arg[], int length) { }

❖ In the code above, the first parameter (int arg[]) accepts any array whose elements are of type int, whatever its length. For that reason, we have included a second parameter that tells the function the length of each array that we pass to it as its first parameter.

Page 218: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Library Arrays❖ The arrays explained so far are directly implemented as a language feature, inherited from the C

language. They are a great feature, but can be a pain, especially for those coming from another language.

❖ To overcome some of these issues with language built-in arrays, C++ provides an alternative array type as a standard container. It is a type template (a class template, in fact) defined in header <array>.

❖ Just as an example, these are two versions of the same example using the language built-in array and the container in the library:

❖ As you can see, both kinds of arrays use the same syntax to access its elements: myarray[i]. Other than that, the main differences lay on the declaration of the array, and the inclusion of an additional header for the library array. Notice also how it is easy to access the size of the library array.

Built-in Array Standard Template Library Arrayint main() { int myarray[3] = {10,20,30}; for (int i=0; i<3; ++i) ++myarray[i]; for (int elem : myarray) cout << elem << endl;} // main

int main() { array<int,3> myarray {10,20,30}; for (int i=0; i<myarray.size(); ++i) ++myarray[i]; for (int elem : myarray) cout << elem << endl; } // main

Page 219: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Character Sequences❖ The string class has been briefly introduced previously. It is a very powerful

class to handle and manipulate strings of characters. However, because strings are, in fact, sequences of characters, we can represent them also as plain arrays of elements of a character type (these are known as C-Strings).

char foo [20];

❖ Therefore, this array has a capacity to store sequences of up to 20 characters. But this capacity does not need to be fully exhausted: the array can also accommodate shorter sequences.

❖ By convention, the end of strings represented in character sequences is signaled by a special character: the null character, whose literal value can be written as '\0' (backslash, zero).

Page 220: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Initialization of Null-Terminated Character Sequences

❖ Because arrays of characters are ordinary arrays, they follow the same rules as these.

❖ For example, to initialize an array of characters with some predetermined sequence of characters, we can do it just like any other array:

char myword[] = { 'H', 'e', 'l', 'l', 'o', '\0' };

❖ The above declares an array of 6 elements of type char initialized with the characters that form the word "Hello" plus a null character '\0' at the end.

❖ But arrays of character elements have another way to be initialized: using string literals directly.

char myword[] = "Hello";

Page 221: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Assignment to Null-Terminated Character Sequences

❖ Since null-terminated character sequences are arrays, you cannot assign value to them directly (even using string literals). char myword[] = "Hello";myword = "Bye"; // won’t compile

❖ This is because arrays cannot be assigned values. Note, though, that each of its elements can be assigned a value individually. For example, this would be correct: myword[0] = 'B';myword[1] = 'y';myword[2] = 'e';myword[3] = '\0';

Page 222: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Strings and Null-Terminated Character Sequences

❖ Plain arrays with null-terminated sequences of characters are the typical types used in the C language to represent strings.

❖ In C++, even though the standard library defines a specific type for strings (class string), still, plain arrays with null-terminated sequences of characters (C-strings) are a natural way of representing strings in the language; in fact, string literals still always produce null-terminated character sequences, and not string objects.

❖ In the standard library, both representations for strings coexist, and most functions requiring strings are overloaded to support both.

❖ Null-terminated character sequences can be transformed into strings implicitly, and strings can be transformed into null-terminated character sequences by using either of string's member functions c_str or data:char myntcs[] = "some text";string mystring = myntcs; // convert c-string to string cout << mystring; // printed as a library string cout << mystring.c_str(); // printed as a c-string

Page 223: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Pointers❖ So far, variables have been explained as locations in the computer's memory which

can be accessed by their identifier (their name).

❖ This way, the program does not need to care about the physical address of the data in memory; it simply uses the identifier whenever it needs to refer to the variable.

❖ For a C++ program, the memory of a computer is like a succession of memory cells, each one byte in size, and each with a unique address. These single-byte memory cells are ordered in a way that allows data representations larger than one byte to occupy memory cells that have consecutive addresses.

❖ This way, each cell can be easily located in the memory by means of its unique address. For example, the memory cell with the address 1776 always follows immediately after the cell with address 1775 and precedes the one with 1777, and is exactly one thousand cells after 776 and exactly one thousand cells before 2776.

Page 224: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Pointers❖ When a variable is declared, the memory needed to store its value

is assigned a specific location in memory (its memory address).

❖ Generally, C++ programs do not actively decide the exact memory addresses where its variables are stored.

❖ Fortunately, that task is left to the environment where the program is run - generally, an operating system that decides the particular memory locations on runtime.

❖ However, it may be useful for a program to be able to obtain the address of a variable during runtime in order to access data cells that are at a certain position relative to it.

Page 225: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Reference Operator❖ The address of a variable can be obtained by preceding the name of

a variable with an ampersand sign (&), known as reference operator, and which can be literally translated as "address of". For example:

foo = &myvar;

❖ This would assign the address of variable myvar to foo; by preceding the name of the variable myvar with the reference operator (&), we are no longer assigning the content of the variable itself to foo, but its address.

❖ The actual address of a variable in memory cannot be known before runtime.

Page 226: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Reference Operator❖ Let's assume, in order to help clarify some concepts, that myvar is placed

during runtime in the memory address 1776.

❖ In this case, consider the following code fragment:myvar = 25;foo = &myvar;bar = myvar;

❖ The values contained in each variable after the execution of this are shown in the following diagram:

We’ll discuss what the types of these variables are in a little bit

Page 227: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Pointers

❖ A variable that stores the address of another variable (like foo on the previous slide) is what in C++ is called a pointer.

❖ Pointers are a very powerful feature of the language that has many uses in lower level programming.

❖ A bit later, we will see how to declare and use pointers.

Page 228: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Dereference Operator❖ As just seen, a variable which stores the address of another variable is

called a pointer. Pointers are said to "point to" the variable whose address they store.

❖ An interesting property of pointers is that they can be used to access the variable they point to directly. This is done by preceding the pointer name with the dereference operator (*). The operator itself can be read as "value pointed to by”.

baz = *foo;

❖ This could be read as: “set baz equal to the value pointed to by foo", and the statement would actually assign the value 25 to baz, since foo is 1776, and the value pointed to by 1776 (following the example above) would be 25.

Page 229: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Dereference Operator

❖ It is important to clearly differentiate that foo refers to the value 1776, while *foo (with an asterisk * preceding the identifier) refers to the value stored at address 1776, which in this case is 25. Notice the difference of including or not including the dereference operator (I have added an explanatory comment of how each of these two expressions could be read): baz = foo; // baz equal to foo (1776)baz = *foo; // baz equal to value pointed to by foo (25)

baz = *foo;

Page 230: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Reference and Dereference Operators❖ The reference and dereference operators are thus complementary:

❖ & is the reference operator, and can be read as "address of"

❖ * is the dereference operator, and can be read as "value pointed to by"

❖ Thus, they have sort of opposite meanings: A variable referenced with & can be dereferenced with *. Earlier, we performed the following two assignment operations:myvar = 25;foo = &myvar;

❖ Right after these two statements, all of the following expressions would give true as result:myvar == 25&myvar == 1776foo == 1776*foo == 25 myvar

Page 231: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Declaring Pointers❖ Due to the ability of a pointer to directly refer to the value that it points to, a

pointer has different properties when it points to a char than when it points to an int or a float.

❖ Once dereferenced, the type needs to be known. And for that, the declaration of a pointer needs to include the data type the pointer is going to point to.

❖ The declaration of pointers follows this syntax:type * name;

where type is the data type pointed to by the pointer. This type is not the type of the pointer itself, but the type of the data the pointer points to. int * number;char * character;double * decimals;

Page 232: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Pointers Example 1int firstvalue, secondvalue;int * mypointer;mypointer = &firstvalue;*mypointer = 10;mypointer = &secondvalue;*mypointer = 20;cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl;

Page 233: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Pointers Example 1int firstvalue, secondvalue;int * mypointer;mypointer = &firstvalue;*mypointer = 10;mypointer = &secondvalue;*mypointer = 20;cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl;

Output: firstvalue is 10 secondvalue is 20

Page 234: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Pointers Example 2int firstvalue = 5, secondvalue = 15;int * p1, * p2;p1 = &firstvalue; // p1 = address of firstvalue p2 = &secondvalue; // p2 = address of secondvalue *p1 = 10; // value pointed to by p1 = 10 *p2 = *p1; // value pointed to by p2 = value pointed by p1 p1 = p2; // p1 = p2 (value of pointer is copied) *p1 = 20; // value pointed by p1 = 20 cout << "firstvalue is " << firstvalue << '\n'; cout << "secondvalue is " << secondvalue << '\n';

Page 235: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Pointers Example 2int firstvalue = 5, secondvalue = 15;int * p1, * p2;p1 = &firstvalue; // p1 = address of firstvalue p2 = &secondvalue; // p2 = address of secondvalue *p1 = 10; // value pointed to by p1 = 10 *p2 = *p1; // value pointed to by p2 = value pointed by p1 p1 = p2; // p1 = p2 (value of pointer is copied) *p1 = 20; // value pointed by p1 = 20 cout << "firstvalue is " << firstvalue << '\n'; cout << "secondvalue is " << secondvalue << '\n';

Output: firstvalue is 10 secondvalue is 20

Page 236: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Pointers Example 2int firstvalue = 5, secondvalue = 15;int * p1, * p2;p1 = &firstvalue; // p1 = address of firstvalue p2 = &secondvalue; // p2 = address of secondvalue *p1 = 10; // value pointed to by p1 = 10 *p2 = *p1; // value pointed to by p2 = value pointed by p1 p1 = p2; // p1 = p2 (value of pointer is copied) *p1 = 20; // value pointed by p1 = 20 cout << "firstvalue is " << firstvalue << '\n'; cout << "secondvalue is " << secondvalue << '\n';

Output: firstvalue is 10 secondvalue is 20

Due to C++ precedence rules, an asterisk is

required for each pointer.

Page 237: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1302 - Software Development

Be Careful Declaring Pointersint * p1, * p2;

int * p1, p2;

int * p1;int * p2;int * p1;int p2;

equivalent to

equivalent to

Page 238: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Reminders❖ Project 1 is due MON 2016-09-19

@ 11:55 PM. 

❖ Description posted on eLC.

❖ Exam 1 is THU 2016-09-29 @ 6PM

❖ Room TBD

❖ General Note

❖ Try to submit your brainstorms before the end of you lab period.

❖ The rest of the lab period should be used to collaborate and work on the lab.

Page 239: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointers and Arrays❖ The concept of arrays is related to that of pointers.

❖ In fact, arrays work very much like pointers to their first elements, and, actually, an array can always be implicitly converted to the pointer of the proper type. int myarray [20];int * mypointer;

❖ The following assignment operation would be valid: mypointer = myarray;

❖ After that, mypointer and myarray would be equivalent and would have very similar properties. The main difference being that mypointer can be assigned a different address, whereas myarray can never be assigned anything, and will always represent the same block of 20 elements of type int.

Page 240: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Example: Arrays and Pointers

int numbers [5];int * p;p = numbers; *p = 10;p++; *p = 20;p = &numbers[2]; *p = 30;p = numbers + 3; *p = 40;p = numbers; *(p+4) = 50;for (int n=0; n<5; n++) cout << numbers[n] << ", ";

Page 241: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Example: Arrays and Pointers

Output: 10, 20, 30, 40, 50, int numbers [5];

int * p;p = numbers; *p = 10;p++; *p = 20;p = &numbers[2]; *p = 30;p = numbers + 3; *p = 40;p = numbers; *(p+4) = 50;for (int n=0; n<5; n++) cout << numbers[n] << ", ";

Page 242: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Arrays and Pointers❖ Pointers and arrays support the same set of operations, with the same meaning for both.

❖ The main difference being that pointers can be assigned new addresses, while arrays cannot.

❖ Earlier, brackets ([]) were explained as specifying the index of an element of the array. Well, in fact these brackets are a dereferencing operator known as offset operator. They dereference the variable they follow just as * does, but they also add the number between brackets to the address being dereferenced. For example: a[5] = 0; // a [offset of 5] = 0*(a+5) = 0; // pointed by (a+5) = 0

❖ These two expressions are equivalent and valid, not only if a is a pointer, but also if a is an array. Remember that if an array, its name can be used just like a pointer to its first element.

Page 243: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointer Initialization❖ Pointers can be initialized to point to specific locations at the very moment they are defined:int myvar;int * myptr = &myvar;

❖ The resulting state of variables after this code is the same as after:int myvar;int * myptr;myptr = &myvar;

When pointers are initialized, what is initialized is the address they point to (i.e., myptr), never the value being pointed (i.e., *myptr). Therefore, the code above shall not be confused with: int myvar;int * myptr;*myptr = &myvar;

Page 244: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointer Arithmetic❖ To conduct arithmetical operations on pointers is a little different than to

conduct them on regular integer types.

❖ Only addition and subtraction operations are allowed.

❖ The others make no sense in the world of pointers.

❖ Both addition and subtraction have a slightly different behavior with pointers, according to the size of the data type to which they point.

❖ When fundamental data types were introduced, we saw that types have different sizes.

❖ For example: char always has a size of 1 byte, short is generally larger than that, and int and long are even larger; the exact size of these being dependent on the system.

Page 245: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointer Arithmetic❖ Let's imagine that in a given system, char takes 1 byte, short takes 2 bytes, and long takes 4.

❖ Suppose now that we define three pointers in this compiler: char * mychar;short * myshort;long * mylong;and that we know that they point to the memory locations 1000, 2000, and 3000, respectively.

❖ Therefore, if we write: ++mychar;++myshort;++mylong;

❖ What are the new values contained in mychar, myshort, and mylong?

Page 246: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointer Arithmetic❖ Let's imagine that in a given system, char takes 1 byte, short takes 2 bytes, and long takes 4.

❖ Suppose now that we define three pointers in this compiler: char * mychar;short * myshort;long * mylong;and that we know that they point to the memory locations 1000, 2000, and 3000, respectively.

❖ Therefore, if we write: ++mychar;++myshort;++mylong;

❖ What are the new values contained in mychar, myshort, and mylong?

mychar now points to 1001

Page 247: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointer Arithmetic❖ Let's imagine that in a given system, char takes 1 byte, short takes 2 bytes, and long takes 4.

❖ Suppose now that we define three pointers in this compiler: char * mychar;short * myshort;long * mylong;and that we know that they point to the memory locations 1000, 2000, and 3000, respectively.

❖ Therefore, if we write: ++mychar;++myshort;++mylong;

❖ What are the new values contained in mychar, myshort, and mylong?

mychar now points to 1001 myshort now points to 2002

Page 248: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointer Arithmetic❖ Let's imagine that in a given system, char takes 1 byte, short takes 2 bytes, and long takes 4.

❖ Suppose now that we define three pointers in this compiler: char * mychar;short * myshort;long * mylong;and that we know that they point to the memory locations 1000, 2000, and 3000, respectively.

❖ Therefore, if we write: ++mychar;++myshort;++mylong;

❖ What are the new values contained in mychar, myshort, and mylong?

mychar now points to 1001 myshort now points to 2002 mylong now points to 3004

Page 249: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointer Arithmetic❖ When adding one to a pointer, the pointer is made to point to

the following element of the same type, and, therefore, the size in bytes of the type it points to is added to the pointer.

Page 250: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Increment and Decrement in Pointer Arithmetic

❖ The increment (++) and decrement (--) operators can be used as either prefix or suffix of an expression, with a slight difference in behavior (as you know).

❖ This also applies to expressions incrementing and decrementing pointers, which can become part of more complicated expressions that also include dereference operators (*).

❖ According to the operator precedence rules, postfix operators, such as increment and decrement, have higher precedence than prefix operators, such as the dereference operator (*).

*p++ // equivalent to *(p++)

❖ What the expression above does is to increase the value of p (so it now points to the next element), but because ++ is used as postfix, the whole expression is evaluated as the value pointed originally by the pointer (the address it pointed to before being incremented).

Page 251: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Increment and Decrement in Pointer Arithmetic

❖ Essentially, these are the four possible combinations of the dereference operator with both the prefix and suffix versions of the increment operator (the same being applicable also to the decrement operator): *p++ // same as *(p++)*++p // same as *(++p)++*p // same as ++(*p)(*p)++ // dereference, and post-increment the value it points to

Page 252: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Increment and Decrement in Pointer Arithmetic

❖ A typical -but not so simple- statement involving these operators is:

*p++ = *q++

Page 253: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Increment and Decrement in Pointer Arithmetic

❖ A typical -but not so simple- statement involving these operators is:*p++ = *q++

❖ Because ++ has a higher precedence than *, both p and q are incremented, but because both increment operators (++) are used as postfix and not prefix, the value assigned to *p is *q before both p and q are incremented. And then both are incremented. It would be roughly equivalent to: *p = *q;++p;++q;

Page 254: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointers and const❖ Pointers can be used to access a variable by its address, and this access

may include modifying the value pointed.

❖ But it is also possible to declare pointers that can access the pointed value to read it, but not to modify it.

❖ For this, it is enough with qualifying the type pointed by the pointer as const.int x;int y = 10;const int * p = &y;x = *p; // ok: reading p*p = x; // error: modifying p, which is const-qualified

Page 255: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointers and const

❖ One of the use cases of pointers to const elements is as function parameters: a function that takes a pointer to non-const as parameter can modify the value passed as argument, while a function that takes a pointer to const as parameter cannot.

Page 256: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointers and const Examplevoid increment_all(int * start, int * stop) { int * current = start; while (current != stop) { ++(*current); // increment value pointed ++current; // increment pointer } // while} // increment_allvoid print_all(const int * start, const int * stop) { const int * current = start; while (current != stop) { cout << *current << endl; ++current; // increment pointer } // while} // print_allint main() { int numbers[] = {10, 20, 30}; increment_all(numbers, numbers + 3); print_all(numbers, numbers + 3); return 0;} // main

Page 257: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointers and const Examplevoid increment_all(int * start, int * stop) { int * current = start; while (current != stop) { ++(*current); // increment value pointed ++current; // increment pointer } // while} // increment_allvoid print_all(const int * start, const int * stop) { const int * current = start; while (current != stop) { cout << *current << endl; ++current; // increment pointer } // while} // print_allint main() { int numbers[] = {10, 20, 30}; increment_all(numbers, numbers + 3); print_all(numbers, numbers + 3); return 0;} // main

Output: 112131

Note that print_all uses pointers that point to constant elements. These pointers point to constant content they cannot modify, but they are not constant themselves: i.e., the pointers can still be incremented or assigned different addresses, although they cannot modify the content they point to.

Page 258: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

const Pointers to const❖ Pointers can themselves be const.

❖ And this is specified by appending const after the asterisk: int x; int * p1 = &x; // non-const pointer to non-const int const int * p2 = &x; // non-const pointer to const int int * const p3 = &x; // const pointer to non-const int const int * const p4 = &x; // const pointer to const int

❖ The syntax with const and pointers is definitely tricky, and recognizing the cases that best suit each use tends to require some experience. In any case, it is important to get constness with pointers (and references) right sooner rather than later, but you should not worry too much about grasping everything if this is the first time you are exposed to the mix of const and pointers.

Page 259: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

const pointers

to const v

ariables:

Oh bother…

Page 260: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Oh, there’s more…❖ To add a little bit more confusion to the syntax of const

with pointers, the const qualifier can either precede or follow the pointed type, with the exact same meaning: const int * p2a = &x; // non-const pointer to const int int const * p2b = &x; // also non-const pointer to const int

❖ As with the spaces surrounding the asterisk, the order of const in this case is simply a matter of style. By convention, we’ll use const as prefix const.

Page 261: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointers and String Literals

❖ As pointed earlier, string literals are arrays containing null-terminated character sequences.

❖ So far, string literals have been used to be directly inserted into cout, to initialize strings and to initialize arrays of characters.

❖ However, they can also be accessed directly. String literals are arrays of the proper array type to contain all its characters plus the terminating null-character, with each of the elements being of type const char (as literals, they can never be modified).

Page 262: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointers and String Literalsconst char * foo = "hello";

❖ This declares an array with the literal representation for "hello", and then a pointer to its first element is assigned to foo.

❖ If we imagine that "hello" is stored at the memory locations that start at address 1702, we can represent the previous declaration as:

❖ Note that here foo is a pointer and contains the value 1702, and not 'h', nor "hello", although 1702 indeed is the address of both of these.

Page 263: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointers and String Literals

❖ The pointer foo points to a sequence of characters. And because pointers and arrays behave essentially in the same way in expressions, foo can be used to access the characters in the same way arrays of null-terminated character sequences are.

*(foo + 4)foo[4]

❖ Both expressions have a value of 'o' (the 5th element of the array).

Page 264: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointers to Pointers❖ C++ allows the use of pointers that point to pointers, that

these, in its turn, point to data (or even to other pointers).

❖ The syntax simply requires an asterisk (*) for each level of indirection in the declaration of the pointer: char a;char * b;char ** c;a = 'z';b = &a;c = &b;

This, assuming the randomly chosen memory locations for each variable of 7230, 8092, and 10502, could be represented as:

Page 265: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointers to Pointerschar a;char * b;char ** c;a = 'z';b = &a;c = &b;

This, assuming the randomly chosen memory locations for each variable of 7230, 8092, and 10502, could be represented as:

The new thing in this example is variable c, which is a pointer to a pointer, and can be used in three different levels of indirection, each one of them would correspond to a different value:

• c is of type char** and a value of 8092• *c is of type char* and a value of 7230• **c is of type char and a value of 'z'

Page 266: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

void Pointers

❖ The void type of pointer is a special type of pointer. In C++, void represents the absence of type.

❖ Therefore, void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereferencing properties).

❖ This gives void pointers a great flexibility, by being able to point to any data type, from an integer value or a float to a string of characters.

❖ In exchange, they have a great limitation: the data pointed by them cannot be directly dereferenced (which is logical, since we have no type to dereference to), and for that reason, any address in a void pointer needs to be transformed into some other pointer type that points to a concrete data type before being dereferenced.

Page 267: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Invalid Pointers and null Pointers❖ In principle, pointers are meant to point to valid addresses, such as the

address of a variable or the address of an element in an array.

❖ But pointers can actually point to any address, including addresses that do not refer to any valid element.

❖ Typical examples of this are uninitialized pointers and pointers to nonexistent elements of an array: int * p; // uninitialized pointer (local variable) int myarray[10];int * q = myarray + 20; // element out of bounds

❖ Neither p nor q point to addresses known to contain a value, but none of the above statements causes an error.

Page 268: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Reminders❖ Project 1 is due MON 2016-09-19 @ 11:55 PM. 

❖ Exam 1 is THU 2016-09-29 @ 6PM in Forestry Resources II 100.

❖ Cheat Sheet: You will are allowed to bring two pages (one standard-sized piece of paper of 8.5 by 11 inches (215.9 mm x 279.4 mm)) of notes that are hand-written to the midterm exam. You will be required to turn in the cheat/note sheet with your exam.

❖ Scheduling Conflicts: If you have another class scheduled at 6PM on 9/29 or a work commitment that causes a time conflict, then please provide verification of the time conflict to your instructor and request a rescheduling of your exam no later than THU 2016-09-22. We will not grant any rescheduling requests for exam 1 after 9/22. Rescheduled exams usually take place the day before or the day after the regularly scheduled exam.

❖ There is no official lecture on the day of the exam (9/29).

ACM First General Body MeetingTODAY (9/8) @ 6 PMBoyd 328

Page 269: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Invalid Pointers and null Pointers❖ What can cause an error is to dereference such a pointer (i.e., actually accessing the

value they point to).

❖ Accessing such a pointer causes undefined behavior, ranging from an error during runtime to accessing some random value.

❖ But, sometimes, a pointer really needs to explicitly point to nowhere, and not just an invalid address.

❖ For such cases, there exists a special value that any pointer type can take: the null pointer value.

❖ This value can be expressed in C++ in two ways: either with an integer value of zero, or with the nullptr keyword:int * p = 0;int * q = nullptr;

Page 270: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Invalid Pointers and null Pointersint * p = 0;int * q = nullptr;

❖ Here, both p and q are null pointers, meaning that they explicitly point to nowhere, and they both actually compare equal: all null pointers compare equal to other null pointers.

❖ It is also quite usual to see the defined constant NULL be used in older code to refer to the null pointer value: int * r = NULL;int * s = nullptr; // C++ >= 11

❖ NULL is defined in several headers of the standard library, and is defined as an alias of some null pointer constant value (such as 0 or nullptr).

Page 271: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

null Pointers and void Pointers

❖ Do not confuse null pointers with void pointers!

❖ A null pointer is a value that any pointer can take to represent that it is pointing to “nowhere"

❖ A void pointer is a type of pointer that can point to somewhere without a specific type.

❖ One refers to the value stored in the pointer, and the other to the type of data it points to.

Page 272: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointers to Functions❖ C++ allows operations with pointers to functions.

❖ The typical use of this is for passing a function as an argument to another function.

❖ Pointers to functions are declared with the same syntax as a regular function declaration, except that the name of the function is enclosed between parentheses () and an asterisk (*) is inserted before the name.

int (* minus)(int, int);

Page 273: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointers to Functions❖ C++ allows operations with pointers to functions.

❖ The typical use of this is for passing a function as an argument to another function.

❖ Pointers to functions are declared with the same syntax as a regular function declaration, except that the name of the function is enclosed between parentheses () and an asterisk (*) is inserted before the name.

int (* minus)(int, int) = subtraction;

❖ Here, minus is a pointer to a function that returns an int that has two parameters of type int. It is directly initialized to point to a function named subtraction.

Page 274: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Function Pointer Example

int addition(int a, int b) { return a + b; } int subtraction(int a, int b) { return a - b; } int operation(int x, int y, int (* functocall)(int, int)) { int g; g = (*functocall)(x, y); return g;} // operationint main() { int m,n; int (* minus)(int, int) = subtraction; m = operation(7, 5, addition); n = operation(20, m, minus); cout << n; return 0;} // main

Page 275: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Function Pointer Example

int addition(int a, int b) { return a + b; } int subtraction(int a, int b) { return a - b; } int operation(int x, int y, int (* functocall)(int, int)) { int g; g = (*functocall)(x, y); return (g);} // operationint main() { int m,n; int (* minus)(int, int) = subtraction; m = operation(7, 5, addition); n = operation(20, m, minus); cout << n; return 0;} // main

Function parameter that is a pointer to a function.

Page 276: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Function Pointer Example

int addition(int a, int b) { return a + b; } int subtraction(int a, int b) { return a - b; } int operation(int x, int y, int (* functocall)(int, int)) { int g; g = (*functocall)(x, y); return g;} // operationint main() { int m,n; int (* minus)(int, int) = subtraction; m = operation(7, 5, addition); n = operation(20, m, minus); cout << n; return EXIT_SUCCESS;} // main

Dereference the function pointer, giving you the function. Apply the function to x and y.

Page 277: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Function Pointer Example

int addition(int a, int b) { return a + b; } int subtraction(int a, int b) { return a - b; } int operation(int x, int y, int (* functocall)(int, int)) { int g; g = (*functocall)(x, y); return g;} // operationint main() { int m,n; int (* minus)(int, int) = subtraction; m = operation(7, 5, addition); n = operation(20, m, minus); cout << n; return EXIT_SUCCESS;} // main

Pointer to a function. Initialize it to point to the subtraction function.

Page 278: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Function Pointer Example

int addition(int a, int b) { return a + b; } int subtraction(int a, int b) { return a - b; } int operation(int x, int y, int (* functocall)(int, int)) { int g; g = (*functocall)(x, y); return g;} // operationint main() { int m,n; int (* minus)(int, int) = subtraction; m = operation(7, 5, addition); n = operation(20, m, minus); cout << n; return EXIT_SUCCESS;} // main

Use a function name directly where a pointer to a function is expected. This makes sense, especially if you consider the semantics of the previous line.

Page 279: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Function Pointer Example

int addition(int a, int b) { return a + b; } int subtraction(int a, int b) { return a - b; } int operation(int x, int y, int (* functocall)(int, int)) { int g; g = (*functocall)(x, y); return g;} // operationint main() { int m,n; int (* minus)(int, int) = subtraction; m = operation(7, 5, addition); n = operation(20, m, minus); cout << n; return EXIT_SUCCESS;} // main

Use a function a function pointer as a parameter in this function call.

Page 280: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Right-Left Rule: Step 1❖ The "right-left" rule is a completely regular rule for deciphering

C/C++ declarations. It can also be useful in creating them.

❖ First, symbols. Read❖ * as "pointer to" - always on the left side

❖ [] as "array of" - always on the right side

❖ () as "function returning" - always on the right side

❖ as you encounter them in the declaration.

❖ STEP 1: Find the identifier. This is your starting point. Then say to yourself, "identifier is." You've started your declaration.

Page 281: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Right-Left Rule: Step 2❖ STEP 2: Look at the symbols on the right of the identifier.

❖ If, say, you find “()" there, then you know that this is the declaration for a function. So you would then have "identifier is function returning".

❖ Or if you found a "[]" there, you would say "identifier is array of”.

❖ Continue right until you run out of symbols *OR* hit a *right* parenthesis ")".

❖ If you hit a left parenthesis, that's the beginning of a () symbol, even if there is stuff in between the parentheses. More on that later.

Page 282: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Right-Left Rule: Step 3❖ STEP 3: Look at the symbols to the left of the identifier.

❖ If it is not one of our symbols from before (say, something like "int"), just say it. Otherwise, translate it into English like we've been doing.

❖ Keep going left until you run out of symbols *OR* hit a *left* parenthesis "(".

❖ Now repeat steps 2 and 3 until you've formed your declaration.

Page 283: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Right-Left Rule

❖ See the following for examples: http://ieng9.ucsd.edu/~cs30x/rt_lt.rule.html

Page 284: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Example❖ Here is the prototype for a function that we’ll use later in the semester:

void (* signal(int signo, void (* func)(int)))(int);

❖ “signal” is a function

❖ with 2 parameters:

❖ signo (an int)

❖ func (a pointer to a function with 1 parameter, an int, that returns void)

❖ that returns a pointer to a function

❖ with 1 parameter:

❖ an int

❖ that returns void

Page 285: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Type Aliases❖ A type alias is a different name by which a type can be identified. In C++, any valid type can

be aliased so that it can be referred to with a different identifier.

❖ One way to create such an alias, inherited from the C language, uses the typedef keyword:typedef existing_type new_type_name;

❖ where existing_type is any type, either fundamental or compound, and new_type_name is an identifier with the new name given to the type.

typedef char C;typedef unsigned int WORD;typedef char * pChar;typedef char field [50];

❖ This defines four type aliases: C, WORD, pChar, and field as char, unsigned int, char* and char[50], respectively. Once these aliases are defined, they can be used in any declaration just like any other valid type.

Page 286: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Type Aliases❖ More recently, a second syntax to define type aliases was introduced in the C++

language:using new_type_name = existing_type;

❖ For example, the same type aliases as above could be defined as:using C = char;using WORD = unsigned int;using pChar = char *;using field = char [50];

❖ Both aliases defined with typedef and aliases defined with using are semantically equivalent. The only difference being that typedef has certain limitations in the realm of templates that using has not. Therefore, using is more generic, although typedef has a longer history and is probably more common in existing code.

Page 287: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Type Aliases

❖ Note that neither typedef nor using create new distinct data types.

❖ They only create synonyms of existing types.

❖ That means that the type of myword on the previous slides, declared with type WORD, can as well be considered of type unsigned int; it does not really matter, since both are actually referring to the same type.

Page 288: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Type Aliases❖ Type aliases can be used to reduce the length of long or

confusing type names, but they are most useful as tools to abstract programs from the underlying types they use.

❖ For example, by using an alias of int to refer to a particular kind of parameter instead of using int directly, it allows for the type to be easily replaced by long (or some other type) in a later version, without having to change every instance where it is used.

Page 289: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Example❖ Here is the prototype for a function that we’ll use later in the semester:

void (* signal(int signo, void (* func)(int)))(int);

❖ Let’s make it easier to read using a typedef:typedef void SigFunc(int);

❖ Now, the original prototype can be written as:SigFunc * signal(int signo, SigFunc * func);

Page 290: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Dynamic Memory❖ So far, all our memory needs were determined before

program execution by defining the variables needed.

❖ But there may be cases where the memory needs of a program can only be determined during runtime. For example, when the memory needed depends on user input.

❖ On these cases, programs need to dynamically allocate memory, for which the C++ language integrates the operators new and delete.

Page 291: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Operators new and new[]❖ Dynamic memory is allocated using operator new. new is followed by a

data type specifier and, if a sequence of more than one element is required, the number of these within brackets [].

❖ It returns a pointer to the beginning of the new block of memory allocated.

❖ Its syntax is: pointer = new typepointer = new type [number_of_elements]

❖ The first expression is used to allocate memory to contain one single element of type type. The second one is used to allocate a block (an array) of elements of type type, where number_of_elements is an integer value representing the amount of these.

Page 292: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Operators new and new[]int * foo;foo = new int [5];

❖ In this case, the system dynamically allocates space for five elements of type int and returns a pointer to the first element of the sequence, which is assigned to foo (a pointer).

❖ Therefore, foo now points to a valid block of memory with space for five elements of type int.

❖ Here, foo is a pointer, and thus, the first element pointed to by foo can be accessed either with the expression foo[0] or the expression *foo (both are equivalent). The second element can be accessed either with foo[1] or *(foo+1), and so on...

Page 293: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Page 294: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Reminders❖ Project 1 is due MON 2016-09-19 @ 11:55 PM. 

❖ Exam 1 is THU 2016-09-29 @ 6PM in Forestry Resources II 100.

❖ Cheat Sheet: You will are allowed to bring two pages (one standard-sized piece of paper of 8.5 by 11 inches (215.9 mm x 279.4 mm)) of notes that are hand-written to the midterm exam. You will be required to turn in the cheat/note sheet with your exam.

❖ Scheduling Conflicts: If you have another class scheduled at 6PM on 9/29 or a work commitment that causes a time conflict, then please provide verification of the time conflict to your instructor and request a rescheduling of your exam no later than THU 2016-09-22. We will not grant any rescheduling requests for exam 1 after 9/22. Rescheduled exams usually take place the day before or the day after the regularly scheduled exam.

❖ There is no official lecture on the day of the exam (9/29).

Page 295: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Plan❖ Demo

❖ Allocate / Deallocate Dynamic Memory

❖ Checking for Memory Leaks with Valgrind

❖ Basic Class❖ Header Guards

❖ Class Header

❖ Separate CPP file

❖ Compile & Link

Page 296: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Live Example!

Let’s write a class!

Page 297: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Dynamic Memory❖ So far, all our memory needs were determined before

program execution by defining the variables needed.

❖ But there may be cases where the memory needs of a program can only be determined during runtime. For example, when the memory needed depends on user input.

❖ On these cases, programs need to dynamically allocate memory, for which the C++ language integrates the operators new and delete.

Page 298: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Operators new and new[]❖ Dynamic memory is allocated using operator new. new is followed by a

data type specifier and, if a sequence of more than one element is required, the number of these within brackets [].

❖ It returns a pointer to the beginning of the new block of memory allocated.

❖ Its syntax is: pointer = new typepointer = new type [number_of_elements]

❖ The first expression is used to allocate memory to contain one single element of type type. The second one is used to allocate a block (an array) of elements of type type, where number_of_elements is an integer value representing the amount of these.

Page 299: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Operators new and new[]int * foo;foo = new int [5];

❖ In this case, the system dynamically allocates space for five elements of type int and returns a pointer to the first element of the sequence, which is assigned to foo (a pointer).

❖ Therefore, foo now points to a valid block of memory with space for five elements of type int.

❖ Here, foo is a pointer, and thus, the first element pointed to by foo can be accessed either with the expression foo[0] or the expression *foo (both are equivalent). The second element can be accessed either with foo[1] or *(foo+1), and so on...

Page 300: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Dynamic Memory and Arrays❖ There is a substantial difference between declaring a normal array

and allocating dynamic memory for a block of memory using new.

❖ The most important difference is that the size of a regular array needs to be a constant expression, and thus its size has to be determined at the moment of designing the program, before it is run.

❖ The dynamic memory allocation performed by new allows to assign memory during runtime using any variable value as size.

❖ Dynamic memory that is requested is allocated by the system from the memory heap.

Page 301: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Dynamic Memory and the Heap❖ As we just mentioned, dynamic memory that is

requested is allocated by the system from the memory heap.

❖ However, computer memory is a limited resource, and it can be exhausted. Therefore, there are no guarantees that all requests to allocate memory using operator new are going to be granted by the system.

❖ C++ provides two standard mechanisms to check if the allocation was successful: exceptions and nothrow.

Page 302: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Handling Dynamic Memory Allocation

❖ Handling Exceptions: Using this method, an exception of type bad_alloc is thrown when the allocation fails.

❖ Exceptions are a powerful C++ feature that we’ll explain later.

❖ For now, you should know that if this exception is thrown and it is not handled by a specific handler, the program execution is terminated.

❖ This exception method is the method used by default by new, and is the one used in a declaration like:

foo = new int [5];

Page 303: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

nothrow❖ nothrow: what happens when it is used is that when a memory allocation fails, instead of throwing a bad_alloc exception or terminating the program, the pointer returned by new is a null pointer, and the program continues its execution normally.

❖ This method can be specified by using a special object called nothrow, declared in header <new>, as argument for new:

foo = new (nothrow) int [5];

❖ In the following case, if the allocation of this block of memory fails, the failure can be detected by checking if foo is a null pointer: int * foo;foo = new (nothrow) int [5];if (foo == nullptr) { // error allocating memory. handle it.} // if

❖ This nothrow method is likely to produce less efficient code than exceptions, since it implies explicitly checking the pointer value returned after each and every allocation. Therefore, the exception mechanism is generally preferred, at least for critical allocations.

Page 304: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Operators delete and delete[]❖ In most cases, memory allocated dynamically is only needed during specific

periods of time within a program; once it is no longer needed, it can be freed so that the memory becomes available again for other requests of dynamic memory.

❖ This is the purpose of operator delete, whose syntax is: delete pointer;delete[] pointer;

❖ The first statement releases the memory of a single element allocated using new, and the second one releases the memory allocated for arrays of elements using new and a size in brackets ([]).

❖ The value passed as argument to delete shall be either a pointer to a memory block previously allocated with new, or a null pointer (in the case of a null pointer, delete produces no effect).

Page 305: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

new and delete Exampleint main() { int i, n; int * p; cout << "How many numbers would you like to type? "; cin >> i; p = new (nothrow) int [i]; if (p == nullptr) { cout << "Error: memory could not be allocated"; } else { for (n = 0; n < i; n++) { cout << "Enter number: "; cin >> p[n]; } // for cout << "You have entered: "; for (n = 0; n < i; n++) cout << p[n] << ", "; delete[] p; } // if return EXIT_SUCCESS;} // main

Page 306: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

valgrind$ whatis valgrind

valgrind (1) - a suite of tools for debugging and profiling programs

❖ You can use valgrind to check for memory leaks. For example, let’s say you want to check your p1 for memory leaks:

$ valgrind ./p1

❖ If you don’t have any memory leaks, then you’ll see this:LEAK SUMMARY: definitely lost: 0 bytes in 0 blocks indirectly lost: 0 bytes in 0 blocks possibly lost: 0 bytes in 0 blocks

❖ If you see a leak, then you can rerun valgrind with --leak-check=full for more information (assuming you compiled with -g).

Page 307: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Data Structures❖ A data structure is a group of data elements grouped together under one name. These data

elements, known as members, can have different types and different lengths.

❖ Data structures can be declared in C++ using the following syntax: struct type_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; . .} object_names;

❖ Where type_name is a name for the structure type, object_name can be a set of valid identifiers for objects that have the type of this structure.

❖ Within braces {}, there is a list with the data members, each one is specified with a type and a valid identifier as its name.

Page 308: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Data Structures Example 1struct product { int weight; double price;};product apple;product banana, melon;

❖ This declares a structure type, called product, and defines it having two members: weight and price, each of a different fundamental type.

❖ This declaration creates a new type (product), which is then used to declare three objects (variables) of this type: apple, banana, and melon.

❖ Note how once product is declared, it is used just like any other type.

Page 309: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Data Structures Example 2❖ Right at the end of the struct definition, and before the ending semicolon (;),

the optional field object_names can be used to directly declare objects of the structure type.

❖ For example, the structure objects apple, banana, and melon can be declared at the moment the data structure type is defined: struct product { int weight; double price;} apple, banana, melon;

❖ In this case, where object_names are specified, the type name (product) becomes optional: struct requires either a type_name or at least one name in object_names, but not necessarily both.

Page 310: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Data Structures❖ Once the three objects of a determined structure type are declared its members can be accessed

directly.

❖ The syntax for that is simply to insert a dot (.) between the object name and the member name.

❖ For example, based on our previous example, we could operate with any of these elements as if they were standard variables of their respective types: apple.weightapple.pricebanana.weightbanana.pricemelon.weightmelon.price

❖ Each one of these has the data type corresponding to the member they refer to: apple.weight, banana.weight, and melon.weight are of type int, while apple.price, banana.price, and melon.price are of type double.

Page 311: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointers to Structures❖ Like any other type, structures can be pointed to by its own type of pointers:struct movies_t { string title; int year;};movies_t amovie;movies_t * pmovie;

❖ Here amovie is an object of structure type movies_t, and pmovie is a pointer to point to objects of structure type movies_t. Therefore, the following code would also be valid:pmovie = &amovie;

❖ The value of the pointer pmovie would be assigned the address of object amovie.

Page 312: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointers to Structures: The Arrow Operator

❖ The arrow operator (->) is a dereference operator that is used exclusively with pointers to objects that have members (structs and classes).

❖ This operator serves to access the member of an object directly from its address.

❖ The following are equivalent:(*pmovie).titlepmovie->title

❖ The following panel summarizes possible combinations of the operators for pointers and for structure members:

Expression

What is Evaluated Equivalenta.b member b of object a

a->b member b of object pointed to by a (*a).b*a.b value pointed to by member b of object a *(a.b)

*a->b value pointed to by member b of object pointed to by a *(*a).b

Page 313: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Nesting Structures❖ Structures can also be nested in such a way that an element of a structure is

itself another structure:❖ struct movies_t { string title; int year;};struct friends_t { string name; string email; movies_t favorite_movie;} charlie, maria;friends_t * pfriends = &charlie;

❖ After these declarations, all of the following expressions would be valid:

charlie.namemaria.favorite_movie.titlecharlie.favorite_movie.yearpfriends->favorite_movie.year

❖ The last two expressions refer to the same member.

Page 314: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Unions❖ Unions allow one portion of memory to be accessed as different data types.

❖ Its declaration and use is similar to the one of structures, but its functionality is totally different:union type_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; . .} object_names;

❖ This creates a new union type, identified by type_name, in which all its member elements occupy the same physical space in memory. The size of this type is the one of the largest member element.

Page 315: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Unions Example 1union mytypes_t { char c; int i; float f;} mytypes;

❖ declares an object (mytypes) with three members:

mytypes.cmytypes.imytypes.f

❖ Each of these members is of a different data type. But since all of them are referring to the same location in memory, the modification of one of the members will affect the value of all of them.

❖ It is not possible to store different values in them in a way that each is independent of the others.

Page 316: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Unions❖ One of the uses of a union is to be able to access a value either in its entirety or as an array or

structure of smaller elements.union mix_t { int l; struct { short hi; short lo; } s; char c[4];} mix;

❖ If we assume that the system where this program runs has an int type with a size of 4 bytes, and a short type of 2 bytes, the union defined above allows the access to the same group of 4 bytes: mix.l, mix.s and mix.c, and which we can use according to how we want to access these bytes: as if they were a single value of type int, or as if they were two values of type short, or as an array of char elements, respectively. The example mixes types, arrays, and structures in the union to demonstrate different ways to access the data.

The exact alignment and order of the members of a union in memory depends on the system, with the possibly of creating portability issues.

Page 317: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Anonymous Unions❖ Unions can also be declared with no type name or object name. In this

case, they become anonymous unions, and its members are directly accessible by their member names. For example, look at the differences between these two structure declarations:

❖ The only difference between the two pieces of code is that in the first one, the union has a name (price), while in the second it has not. This affects the way to access members dollars and yen of an object of this type.

regular union anonymous unionstruct { char title[50]; char author[50]; union { float dollars; int yen; } price; } book;

struct { char title[50]; char author[50]; union { float dollars; int yen; }; } book;

Page 318: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Anonymous Unions

❖ For an object of the first type (a regular union), it would be:

book.price.dollarsbook.price.yen

regular union anonymous unionstruct { char title[50]; char author[50]; union { float dollars; int yen; } price; } book;

struct { char title[50]; char author[50]; union { float dollars; int yen; }; } book;

❖ For an object of the second type (a regular union), it would be:

book.dollarsbook.yen

Again, remember that because it is a union (not a structure), the members dollars and yen actually share the same memory location, so they cannot be used to store two different values simultaneously. The price

can be set in dollars or in yen, but not in both simultaneously.

Page 319: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Enumerated Types❖ Enumerated types are types that are defined with a set of custom identifiers, known

as enumerators, as possible values. Objects of these enumerated types can take any of these enumerators as value.

❖ Their syntax is:enum type_name { value1, value2, value3, . .} object_names;

❖ This creates the type type_name, which can take any of value1, value2, value3, ... as value. Objects (variables) of this type can directly be instantiated as object_names.

Page 320: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Enumerated Types❖ A new type of variable called colors_t could be defined to store

colors with the following declaration: ❖ enum colors_t { black, blue, green, cyan, red, purple, yellow, white };

❖ Notice that this declaration includes no other type, neither fundamental nor compound, in its definition. To say it another way, somehow, this creates a whole new data type from scratch without basing it on any other existing type.

❖ Contrast that with structs, which do create whole new data types but are based on existing types.

Page 321: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Enumerated Types❖ The possible values that variables of this new type color_t may

take are the enumerators listed within braces.

❖ For example, once the colors_t enumerated type is declared, the following expressions will be valid:colors_t mycolor; mycolor = blue;if (mycolor == green) mycolor = red;

Page 322: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Enumerated Types and int❖ Values of enumerated types declared with enum are implicitly

convertible to the integer type int, and vice versa.

❖ In fact, the elements of such an enum are always assigned an integer numerical equivalent internally, of which they become an alias.

❖ If it is not specified otherwise, the integer value equivalent to the first possible value is 0, the equivalent to the second is 1, to the third is 2, and so on...

❖ Therefore, in the data type colors_t defined above, black would be equivalent to 0, blue would be equivalent to 1, green to 2, and so on..

Page 323: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Enumerated Types and int❖ A specific integer value can be specified for any of the possible values in the

enumerated type.

❖ And if the constant value that follows it is itself not given its own value, it is automatically assumed to be the same value plus one.

❖ enum months_t { january=1, february, march, april, may, june, july, august, september, october, november, december} y2k;

❖ In this case, the variable y2k of the enumerated type months_t can contain any of the 12 possible values that go from january to december and that are equivalent to the values between 1 and 12 (not between 0 and 11, since january has been made equal to 1).

Page 324: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Enumerated Types and int❖ Because enumerated types declared with enum are implicitly

convertible to int, and each of the enumerator values is actually of type int, there is no way to distinguish 1 from january - they are the exact same value of the same type. ❖ In other words, the following are equivalent statements: y2k = 1;y2k = january;

❖ The reasons for this are historical and are inheritance of the C language.

Page 325: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Enumerated Types with enum class❖ In C++, it is possible to create real enum types that are neither implicitly

convertible to int and that neither have enumerator values of type int, but of the enum type itself, thus preserving type safety.

❖ They are declared with enum class (or enum struct) instead of just enum:enum class Colors { black, blue, green, cyan, red, purple, yellow, white };

❖ Each of the enumerator values of an enum class type needs to be scoped into its type.Colors mycolor;mycolor = Colors::blue;if (mycolor == Colors::green) mycolor = Colors::red;

Page 326: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Enumerated Types with enum class❖ Enumerated types declared with enum class also have more control

over their underlying type; it may be any integral data type, such as char, short or unsigned int, which essentially serves to determine the size of the type.

❖ This is specified by a colon and the underlying type following the enumerated type.enum class EyeColor : char {blue, green, brown};

❖ Here, Eyecolor is a distinct type with the same size of a char (1 byte).

Page 327: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Classes❖ Classes are an expanded concept of data structures: like data structures, they can contain data

members, but they can also contain functions as members.

❖ An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable.

❖ Classes are defined using either keyword class or keyword struct, with the following syntax:class class_name { access_specifier_1: member1; access_specifier_2: member2; ...} object_names;

❖ Where class_name is a valid identifier for the class, object_names is an optional list of names for objects of this class. The body of the declaration can contain members, which can either be data or function declarations, and optionally access specifiers.

Page 328: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Classes❖ The format is the same as for plain data structures, except that they can also include

functions, and have this new things called access specifiers.

❖ An access specifier is one of the following three keywords: private, public or protected. These specifiers modify the access rights for the members that follow them:

❖ private members of a class are accessible only from within other members of the same class (or from their "friends").

❖ protected members are accessible from other members of the same class (or from their "friends"), but also from members of their derived classes.

❖ Finally, public members are accessible from anywhere where the object is visible.

❖ By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before any other access specifier has private access automatically.

Page 329: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Classesclass Rectangle { int width, height; public: void set_values (int,int); int area (void);} rect;

❖ This example declares a class (i.e., a type) called Rectangle and an object (i.e., a variable) of this class, called rect.

❖ This class contains four members:

❖ two data members of type int (member width and member height) with private access (because private is the default access level) and

❖ two member functions with public access: the functions set_values and area, of which for now we have only included their declaration (prototype), but not their definition.

Page 330: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Classesclass Rectangle { int width, height; public: void set_values (int,int); int area (void);} rect;

❖ After the declarations of Rectangle and rect, any of the public members of object rect can be accessed as if they were normal functions or normal variables, by simply inserting a dot (.) between object name and member name.

❖ This follows the same syntax as accessing the members of plain data structures.rect.set_values (3, 4);myarea = rect.area();

❖ The only members of rect that cannot be accessed from outside the class are width and height, since they have private access and they can only be referred to from within other members of that same class.

Page 331: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Exampleclass Rectangle { int width, height; public: void set_values (int,int); int area() { return width * height; }}; // Rectanglevoid Rectangle::set_values(int x, int y) { width = x; height = y;} // set_values int main() { Rectangle rect; rect.set_values (3,4); cout << "area: " << rect.area() << endl; return 0;} // main

This example reintroduces the scope operator (::, two colons), seen in earlier chapters in relation to namespaces. Here it is used in the definition of function set_values to define a member of a class outside the class itself.

Notice that the definition of the member function area has been included directly within the definition of class Rectangle given its extreme simplicity. Conversely, set_values it is merely declared with its prototype within the class, but its definition is outside it.

In this outside definition, the operator of scope (::) is used to specify that the function being defined is a member of the class Rectangle and not a regular non-member function.

Page 332: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Classes and Scope Operator❖ One use of the scope operator (::) is to specify the class to which the member

being declared belongs, granting exactly the same scope properties as if this function definition was directly included within the class definition.

❖ For example, the function set_values in the previous example has access to the variables width and height, which are private members of class Rectangle, and thus only accessible from other members of the class, such as this.

❖ The only difference between defining a member function completely within the class definition or to just include its declaration in the function and define it later outside the class, is that in the first case the function is automatically considered an inline member function by the compiler, while in the second it is a normal (not-inline) class member function.

❖ This causes no differences in behavior, but only on possible compiler optimizations.

Page 333: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Classes and Access❖ Members width and height have private access (remember that if nothing

else is specified, all members of a class defined with keyword class have private access).

❖ By declaring them private, access from outside the class is not allowed. This makes sense, since we have already defined a member function to set values for those members within the object: the member function set_values.

❖ Therefore, the rest of the program does not need to have direct access to them. Perhaps in a so simple example as this, it is difficult to see how restricting access to these variables may be useful, but in greater projects it may be very important that values cannot be modified in an unexpected way (unexpected from the point of view of the object).

Page 334: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Classes are Typesclass Rectangle { int width, height; public: void set_values (int,int); int area() { return width * height; }}; // Rectanglevoid Rectangle::set_values(int x, int y) { width = x; height = y;} // set_values int main() { Rectangle rect, rectb; rect.set_values(3, 4); rectb.set_values(5, 6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0;} // main

The most important property of a class is that it is a type, and as such, we can declare multiple objects of it.

In this particular case, the class (type of the objects) is Rectangle, of which there are two instances (i.e., objects): rect and rectb. Each one of them has its own member variables and member functions.

Page 335: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Separating it Out❖ In order to divide a classes interface from it’s implementation, it is very common

to place a class’s declaration and prototypes in a header file and its function implementations in a .cpp (or .cc) file.

Rectangle.h:class Rectangle { int width, height; public: void set_values (int,int); int area() { return width * height; } }; // Rectangle

Rectangle.cpp:#include "Rectangle.h"void Rectangle::set_values(int x, int y) { width = x; height = y;} // set_values

main.cpp:#include <iostream>#include "Rectangle.h"using namespace std;int main() { Rectangle rect, rectb; rect.set_values(3, 4); rectb.set_values(5, 6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0;} // main

You could give a developer your Rectangle.h file and a compiled Rectangle.o file. This would allow them to use your class in their own code without ever seeing the implementation.

Page 336: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Constructors❖ What would happen in the previous example if we called the

member function area before having called set_values? An undetermined result, since the members width and height had never been assigned a value.

❖ In order to avoid that, a class can include a special function called its constructor, which is automatically called whenever a new object of this class is created, allowing the class to initialize member variables or allocate storage.

❖ The constructor function is declared just like a regular member function, but with a name that matches the class name and without any return type; not even void.

Page 337: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Constructorsclass Rectangle { int width, height; public: Rectangle(int,int); int area() { return width * height; }}; // RectangleRectangle::Rectangle(int x, int y) { width = x; height = y;} // set_values int main() { Rectangle rect(3,4); Rectangle rectb(5, 6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0;} // main

The results of this example are identical to those of the previous example. But now, class Rectangle has no member function set_values, and has instead a constructor that performs a similar action: it initializes the values of width and height with the arguments passed to it.Notice how these arguments are passed to the constructor at the moment at which the objects of this class are created

Page 338: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Overloading Constructors❖ Like any other function, a constructor can also be overloaded

with different versions taking different parameters: with a different number of parameters and/or parameters of different types.

❖ Just like in Java, the compiler will automatically call the one whose parameters match the arguments

❖ You can even have a default constructor. The default constructor is the constructor that takes no parameters, and it is special because it is called when an object is declared but is not initialized with any arguments.

Page 339: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Initialization of Classes❖ The way of calling constructors by enclosing their arguments in

parentheses is known as functional form.

❖ Constructors can also be called with other syntaxes:

❖ Assignment Form: constructors with a single parameter can be called using the variable initialization syntax (an equal sign followed by the argument). class_name object_name = initialization_value;

❖ Uniform Initialization: essentially is the same as the functional form, but using braces ({}) instead of parentheses (()). class_name object_name { value, value, value, … };

Page 340: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Initialization of Classes❖ An advantage of uniform initialization over functional form is

that, unlike parentheses, braces cannot be confused with function declarations, and thus can be used to explicitly call default constructors:Rectangle rectb; // default constructor called Rectangle rectc(); // function declaration (default constructor NOT called) Rectangle rectd{}; // default constructor called

❖ The choice of syntax to call constructors is largely a matter of style.

❖ Most existing code currently uses functional form, and some newer style guides suggest to choose uniform initialization over the others.

Page 341: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Member Initialization in Constructors❖ When a constructor is used to initialize other members, these other

members can be initialized directly, without resorting to statements in its body.

❖ This is done by inserting, before the constructor's body, a colon (:) and a list of initializations for class members.

❖ Here is another way to write a constructor for our Rectangle class:Rectangle(int x, int y) : width(x), height{y} { }

❖ For members of fundamental types, it makes no difference which of the ways above the constructor is defined, because they are not initialized by default, but for member objects (those whose type is a class), if they are not initialized after the colon, they are default-constructed.

Page 342: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Destructor❖ Destructors fulfill the opposite functionality of

constructors: They are responsible for the necessary cleanup needed by a class when its lifetime ends.

❖ A destructor is a member function very similar to a default constructor: it takes no arguments and returns nothing, not even void. It also uses the class name as its own name, but preceded with a tilde sign (~).

❖ The use case for a destructor would be to deallocate any memory that was allocated by the class during its lifetime.

Page 343: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Exampleclass Example { string* ptr; public: Example() : ptr(new string) {} Example (const string& str) : ptr(new string(str)) {} ~Example () { delete ptr; } const string& content() const { return *ptr; } };int main () { Example foo; Example bar ("Example"); cout << "bar's content: " << bar.content() << endl; return 0;} // main

Page 344: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Copy Constructor❖ When an object is passed a named object of its own type as argument, its

copy constructor is invoked in order to construct a copy.

❖ A copy constructor is a constructor whose first parameter is of type reference to the class itself (possibly const qualified) and which can be invoked with a single argument of this type.

❖ For example, for a class MyClass, the copy constructor may have the following signature:

MyClass::MyClass (const MyClass&);

❖ If a class has no custom copy nor move constructors (or assignments) defined, an implicit copy constructor is provided. This copy constructor simply performs a shallow copy of its own members.

Page 345: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Default Copy Constructor❖ The default copy constructor may suit the needs of many classes, but shallow copies

only copy the members of the class themselves, and this is probably not what we expect for classes like class Example we defined in the destructor example, because it contains pointers and handles its storage.

❖ For that class, performing a shallow copy means that the pointer value is copied, but not the content itself; This means that both objects (the copy and the original) would be sharing a single string object (they would both be pointing to the same object), and at some point (on destruction) both objects would try to delete the same block of memory, probably causing the program to crash on runtime.

❖ This can be solved by defining the following custom copy constructor that performs a deep copy:Example (const Example & x) : ptr(new string(x.content())) {}

Page 346: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Pointers to Classes❖ Objects can also be pointed to by pointers: Once declared, a class

becomes a valid type, so it can be used as the type pointed to by a pointer.

Rectangle * prect;

❖ This example is a pointer to an object of class Rectangle.

❖ Similarly as with plain data structures, the members of an object can be accessed directly from a pointer by using the arrow operator (->).Rectangle * prect = new Rectangle(5, 6);cout << prect->area();delete prect;

Page 347: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

ExamplesRectangle obj(3, 4);Rectangle * foo, * bar, * baz;foo = &obj;bar = new Rectangle (5, 6);baz = new Rectangle[2] { {2,5}, {3,6} };cout << "obj's area: " << obj.area() << endl; cout << "*foo's area: " << foo->area() << endl; cout << "*bar's area: " << bar->area() << endl; cout << "baz[0]'s area:" << baz[0].area() << endl; cout << "baz[1]'s area:" << baz[1].area() << endl; delete bar;delete[] baz;

Page 348: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Classes Defined with struct and union❖ Classes can be defined not only with keyword class, but also with keywords struct and union.

❖ The keyword struct, generally used to declared plain data structures, can also be used to declare classes that have member functions, with the same syntax as with keyword class.

❖ The only difference between both is that members of classes declared with the keyword struct have public access by default, while members of classes declared with the keyword class have private access by default. For all other purposes both keywords are equivalent in this context.

❖ Conversely, the concept of unions is different from that of classes declared with struct and class, since unions only store one data member at a time, but nevertheless they are also classes and can thus also hold member functions. The default access in union classes is public.

Page 349: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Live Example!

Let’s write a class!

Page 350: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Reminders❖ Project 1 is due MON 2016-09-19 @ 11:55 PM. 

❖ Exam 1 is THU 2016-09-29 @ 6PM in Forestry Resources II 100.

❖ Cheat Sheet: You will are allowed to bring two pages (one standard-sized piece of paper of 8.5 by 11 inches (215.9 mm x 279.4 mm)) of notes that are hand-written to the midterm exam. You will be required to turn in the cheat/note sheet with your exam.

❖ Scheduling Conflicts: If you have another class scheduled at 6PM on 9/29 or a work commitment that causes a time conflict, then please provide verification of the time conflict to your instructor and request a rescheduling of your exam no later than THU 2016-09-22. We will not grant any rescheduling requests for exam 1 after 9/22. Rescheduled exams usually take place the day before or the day after the regularly scheduled exam.

❖ There is no official lecture on the day of the exam (9/29).

Page 351: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Plan

❖ Demo

❖ Basic Class❖ Finish implementing.

❖ Const Objects

❖ Dynamic Memory Allocation with Objects

❖ Operator Overloading

Page 352: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Overloading Operators❖ Classes, essentially, define new types to be used in C++ code. And

types in C++ not only interact with code by means of constructions and assignments. They also interact by means of operators. For example, take the following operation on fundamental types:int a, b, c;a = b + c;

❖ Here, different variables of a fundamental type (int) are applied the addition operator, and then the assignment operator. For a fundamental arithmetic type, the meaning of such operations is generally obvious and unambiguous, but it may not be so for certain class types.

Page 353: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Operator Overloadingstruct myclass { string product; float price;} a, b, c;a = b + c;

❖ Here, it is not obvious what the result of the addition operation on b and c does.

❖ In fact, this code alone would cause a compilation error, since the type myclass has no defined behavior for additions.

❖ However, C++ allows most operators to be overloaded so that their behavior can be defined for just about any type, including classes.

Page 354: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Overloading Operators❖ Here is a list of all the operators that can be overloaded:

❖ Operators are overloaded by means of operator functions, which are regular functions with special names: their name begins by the operator keyword followed by the operator sign that is overloaded.

❖ The syntax is:

type operator sign (parameters) { /*... body ...*/ }

+ - * / = < > += -= *= /= << >> <<= >>= == != <= >= ++ -- % & ^ ! | ~ &= ^= |= && || %= [] () , ->* -> new delete new[] delete[]

Page 355: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Example

❖ For example, cartesian vectors are sets of two coordinates: x and y.

❖ The addition operation of two cartesian vectors is defined as the addition both x coordinates together, and both y coordinates together.

❖ For example, adding the cartesian vectors (3,1) and (1,2) together would result in (3+1,1+2) = (4,3).

Page 356: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Example❖ class CVector { public: int x,y; CVector () {}; CVector (int a, int b) : x(a), y(b) {}; CVector operator + (const CVector&);}; // CVectorCVector CVector::operator+ (const CVector& param) { CVector temp; temp.x = x + param.x; temp.y = y + param.y; return temp;} // +int main() { CVector foo {3, 1}; CVector bar {1, 2}; CVector result; result = foo + bar; cout << result.x << ',' << result.y << '\n'; return 0;} // main

Page 357: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Example❖ class CVector { public: int x,y; CVector () {}; CVector (int a, int b) : x(a), y(b) {}; CVector operator + (const CVector&);}; // CVectorCVector CVector::operator+ (const CVector& param) { CVector temp; temp.x = x + param.x; temp.y = y + param.y; return temp;} // +int main() { CVector foo {3, 1}; CVector bar {1, 2}; CVector result; result = foo + bar; cout << result.x << ',' << result.y << '\n'; return 0;} // main

Output:4,3

Page 358: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Example❖ class CVector { public: int x,y; CVector () {}; CVector (int a, int b) : x(a), y(b) {}; CVector operator + (const CVector&);}; // CVectorCVector CVector::operator+ (const CVector& param) { CVector temp; temp.x = x + param.x; temp.y = y + param.y; return temp;} // +int main() { CVector foo {3, 1}; CVector bar {1, 2}; CVector result; result = foo + bar; cout << result.x << ',' << result.y << '\n'; return 0;} // main

Output:4,3

The function operator+ of class CVector overloads the addition operator (+) for that type. Once declared, this function can be called either implicitly using the operator, or explicitly using its functional name:c = a + b; c = a.operator+ (b);

Both expressions are equivalent.

Page 359: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Copy Assignment❖ The copy assignment function/operator copies the whole

content of the data members of the object passed as argument (the one at the right side of the sign) to the one at the left side:CVector d (2,3);CVector e;e = d; // copy assignment operator

❖ The copy assignment member is the only operator implicitly defined for all classes. Of course, it can be redefined to any other functionality, such as, for example, to copy only certain members or perform additional initialization operations.

Page 360: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Overloading Operators

❖ The operator overload functions are just regular functions which can have any behavior; there is actually no requirement that the operation performed by that overload bears a relation to the mathematical or usual meaning of the operator, although it is strongly recommended.

❖ For example, a class that overloads operator+ to actually subtract or that overloads operator== to fill the object with zeros, is perfectly valid, although using such a class could be challenging.

Page 361: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Overloading Operators❖ The parameter expected for a member function overload for operations such as operator+ is naturally the operand to the right hand side of the operator.

❖ This is common to all binary operators (those with an operand to its left and one operand to its right).

❖ But operators can come in diverse forms. Here you have a table with a summary of the parameters needed for each of the different operators than can be overloaded (please, replace @ by the operator in each case):

❖ Where a is an object of class A, b is an object of class B and c is an object of class C. TYPE is just any type (that operators overloads the conversion to type TYPE).

Page 362: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Exampleclass CVector { public: int x,y; CVector () {} CVector (int a, int b) : x(a), y(b) {} };CVector operator+ (const CVector& lhs, const CVector& rhs) { CVector temp; temp.x = lhs.x + rhs.x; temp.y = lhs.y + rhs.y; return temp;} // +int main () { CVector foo (3,1); CVector bar (1,2); CVector result; result = foo + bar; cout << result.x << ',' << result.y << endl; return 0;} // main

Page 363: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Overloading Operators❖ Some operators may be overloaded in two forms: either

as a member function or as a non-member function.❖ If an operator is overloaded as a member function, we

assume the first operand in the operation is an object of the class the function belongs to.

❖ If an operator is overloaded as a non-member function, the first parameter must be an object of the class.

Page 364: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Exampleclass CVector { public: int x,y; CVector () {} CVector (int a, int b) : x(a), y(b) {} };CVector operator+ (const CVector& lhs, const CVector& rhs) { CVector temp; temp.x = lhs.x + rhs.x; temp.y = lhs.y + rhs.y; return temp;} // +int main () { CVector foo (3,1); CVector bar (1,2); CVector result; result = foo + bar; cout << result.x << ',' << result.y << endl; return 0;} // main

We can tell that this is not a member function because it’s not scoped (using ::) to CVector.

Additionally, this function takes two parameters: the first is a reference to an object of type CVector; the second can be any other type (in this case it’s another CVector).

Page 365: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Why Bother with Non-Member Overloads?

❖ When you overload using a member function, you assume the first operand is a reference to an object of the class to which the function belongs.

❖ What if you want the first operand to be not a class type? (For example double).

❖ We could write a non-member function that overloads an operator for double, that takes our class as the second operand.

❖ We’ll cover this scenario specifically when we get to friends of classes.

Page 366: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Move Constructor and Assignment❖ Similar to copying, moving also uses the value of an object

to set the value to another object. But, unlike copying, the content is actually transferred from one object (the source) to the other (the destination): the source loses that content, which is taken over by the destination. This moving only happens when the source of the value is an unnamed object.

❖ Unnamed objects are objects that are temporary in nature, and thus haven't even been given a name. Typical examples of unnamed objects are return values of functions or type-casts.

Page 367: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Static Members❖ A class can contain static members, either data or functions.

❖ A static data member of a class is also known as a "class variable", because there is only one common variable for all the objects of that same class, sharing the same value: i.e., its value is not different from one object of this class to another.

❖ Static members have the same properties as non-member variables but they enjoy class scope. For that reason, and to avoid them to be declared several times, they cannot be initialized directly in the class, but need to be initialized somewhere outside it.

Page 368: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Exampleclass Dummy { public: static int n; Dummy () { n++; }; ~Dummy () { n--; };};int Dummy::n = 0;int main () { Dummy a; Dummy b[5]; Dummy * c = new Dummy; cout << a.n << '\n'; delete c; cout << Dummy::n << '\n'; return 0;} // main

Page 369: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Live Example

❖ Overloading the stream insertion operator (<<) is similar to overriding the toString method in Java.

❖ Let’s see how this works with our GradeBook

Page 370: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Reminders❖ Project 2 is due MON 2016-10-10 @ 11:55 PM. 

❖ Exam 1 is THU 2016-09-29 @ 6PM in Forestry Resources II 100.

❖ Cheat Sheet: You will are allowed to bring two pages (one standard-sized piece of paper of 8.5 by 11 inches (215.9 mm x 279.4 mm)) of notes that are hand-written to the midterm exam. You will be required to turn in the cheat/note sheet with your exam.

❖ Scheduling Conflicts: If you have another class scheduled at 6PM on 9/29 or a work commitment that causes a time conflict, then please provide verification of the time conflict to your instructor and request a rescheduling of your exam no later than THU 2016-09-22. We will not grant any rescheduling requests for exam 1 after 9/22. Rescheduled exams usually take place the day before or the day after the regularly scheduled exam.

❖ Review day on 9/27.

❖ There is no official lecture on the day of the exam (9/29).

Page 371: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Lab 05❖ Submit whatever you have using the submit command.

❖ Be sure to include your README file.❖ Instructions

❖ Reflection

Page 372: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Lab 06❖ Brainstorm

❖ Progress Report

❖ Game Plan

❖ Also submit whatever you have using the submit command before lab 7.

❖ Be sure to include your README file.❖ Instructions

❖ Reflection

Page 373: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Some Team Names…❖ Git Gud git Cotterell

❖ Bits Please

❖ Awesome Team Name

❖ Team Pink

❖ Catz

❖ Mad Lads

❖ DreamTeam

❖ J-Ho

❖ CSCI Admins

❖ Navy Narwhal

❖ Team Yolo

❖ notCreativeEnough

❖ C++ Team

❖ Logical Error

❖ A & Z Programmer

❖ Awesome Team Name

❖ new dude[2]

❖ Team Struggle

❖ I Miss Java

❖ The Dereferenced Destroyers

❖ ClayCo

❖ IT'S HIGH NOON

❖ Strictly Business

❖ Heapsters

❖ Wasabi++

❖ codeAndPray

❖ Java is Better

❖ int elligence;

Page 374: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Questions?

Page 375: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

GDB - The GNU Debugger❖ The purpose of a debugger such as GDB is to allow you to see what is going

on “inside” another program while it executes—or what another program was doing at the moment it crashed.

❖ GDB can do four main kinds of things (plus other things in support of these) to help you catch bugs in the act:

❖ Start your program, specifying anything that might affect its behavior.

❖ Make your program stop on specified conditions.

❖ Examine what has happened, when your program has stopped.

❖ Change things in your program, so you can experiment with correcting the effects of one bug and go on to learn about another.

❖ You can use GDB to debug programs written in C and C++.

Page 376: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Core Files❖ A core file or core dump is a file that records the memory

image of a running process and its process status (register values etc.).

❖ A program that crashes automatically produces a core file, unless this feature is disabled by the user or the core file size exceeds the core file size user limit.

❖ When an automatic core dump produces a core file, the name of the core file defaults to core.pid, where pid is the process ID.

Page 377: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Ensuring Core Files get Generated❖ In Linux, core files are not generated by default when a core dump occurs. This is because the user limit

for the maximum size of a core file is set to 0. If you want to use a core files that was generated via an automatic core dump, you need to change this user limit using the ulimit shell command (assuming bash shell).

❖ To see what the maximum allowed core file size is, use:$ ulimit -H -c

❖ If the output of the above command is 0, then you need to contact the system administrator and request (nicely) that they increase the hard limit for the size of core files. If the output of the above command is not 0, then you may use ulimit set your own soft limit in the range [0, hard_limit].

❖ Let's assume that the command above returned "unlimited" (which is often the case). You can set your soft user limit for the size of core files to unlimited using the following shell command:

$ ulimit -S -c unlimited

❖ Be careful when using the ulimit command. Be sure to read its manual page before doing something you're not sure of.

Page 378: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Invoking GDB❖ Invoke GDB by running the program gdb. Once started, GDB reads commands from the terminal until

you tell it to exit.

❖ You can also run gdb with a variety of arguments and options, to specify more of your debugging environment at the outset.

❖ The command-line options described here are designed to cover a variety of situations; in some environments, some of these options may effectively be unavailable.

❖ The most usual way to start GDB is with one argument, specifying an executable program:$ gdb program

❖ You can also start with both an executable program and a core dump file specified:$ gdb program core

❖ You can, instead, specify a process ID as a second argument, if you want to debug a running process:$ gdb program 1234

would attach GDB to process 1234 (unless you also have a file named 1234; GDB does check for a core dump file first).

Page 379: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Invoking GDB❖ You can optionally have gdb pass any arguments after the executable file to the inferior using --

args. This option stops option processing.$ gdb --args gcc -O2 -c foo.c

❖ This will cause gdb to debug gcc, and to set gcc’s command-line arguments to ‘-O2 -c foo.c’.

❖ You can run gdb without printing the front material, which describes GDB’s non-warranty, by specifying -silent:

$ gdb -silent

❖ You can further control how GDB starts up by using command-line options. GDB itself can remind you of the options available.

$ gdb -help

❖ All options and command line arguments you give are processed in sequential order. The order makes a difference when the ‘-x’ option is used.

Page 380: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Quitting GDB❖ To exit GDB, use the quit command (abbreviated q), or type

an end-of-file character (usually C-d).

❖ An interrupt (often C-c) does not exit from GDB, but rather terminates the action of any GDB command that is in progress and returns to GDB command level.

❖ It is safe to type the interrupt character at any time because GDB does not allow it to take effect until a time when it is safe.

❖ If you have been using GDB to control an attached process or device, you can release it with the detach command.

Page 381: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Symbol Table❖ When we program, we use identifiers for convenience.

❖ When a program is compiled, the resulting assembly does not contain identifier names. The variables and functions we wrote are just locations in memory once the program is loaded.

❖ In order to facilitate debugging, we would like to have information about the identifiers so that we can fix problems. Compilers call the collection of the following information about identifiers the symbol table:

❖ identifier’s memory address,

❖ its source file name, and

❖ its line number.

❖ To ensure the symbol table is added to an object file during compilation, the -g (debugger) flag is generally used:

$ gcc -g -c main.c

Page 382: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Compiler Optimizations❖ Some compilers perform optimizations in order to make

programs more efficient. However, enabling optimizations can result in assembly that does not directly map to the original source code. This can make the symbol table useless.

❖ For this reason, when debugging, it is generally a good idea to disable compiler optimizations.

❖ GCC compilers, by default, do not perform optimizations. If you have a custom build of GCC, it’s generally good to explicitly disable optimizations using the -O0 flag:

$ gcc -g -O0 -c main.cpp

Page 383: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

GDB Shell Commands❖ If you need to execute occasional shell commands during your

debugging session, there is no need to leave or suspend GDB; you can just use the shell command.

(gdb) shell command-string

❖ The utility make is often needed in development environments. You do not have to use the shell command for this purpose in GDB:

(gdb) make make-args

❖ Execute the make program with the specified arguments. This is equivalent to ‘shell make make-args’.

Page 384: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

GDB Logging Output❖ You may want to save the output of GDB commands to a file. There

are several commands to control GDB’s logging.

Command Description

(gdb) set logging on Enable logging

(gdb) set logging off Disable logging

(gdb) set logging file file Change the name of the current logfile.

(gdb) set logging overwrite [on|off] Make GDB overwrite the logfile instead of append.

(gdb) logging redirect [on|off] Make GDB only output log messages to the logfile (and not the screen)

(gdb) show logging Show current logging settings

Page 385: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

GDB Commands

❖ You can abbreviate a GDB command to the first few letters of the command name, if that abbreviation is unambiguous; and you can repeat certain GDB commands by typing just RET.

❖ You can also use the TAB key to get GDB to fill out the rest of a word in a command (or to show you the alternatives available, if there is more than one possibility).

Page 386: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Command Syntax❖ A GDB command is a single line of input.

❖ There is no limit on how long it can be. It starts with a command name, which is followed by arguments whose meaning depends on the command name.

❖ For example, the command step accepts an argument which is the number of times to step, as in ‘step 5’. You can also use the step command with no arguments.

❖ Some commands do not allow any arguments.

Page 387: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Command Syntax❖ GDB command names may always be truncated if that abbreviation

is unambiguous.

❖ Other possible command abbreviations are listed in the documentation for individual commands.

❖ In some cases, even ambiguous abbreviations are allowed; for example, s is specially defined as equivalent to step even though there are other commands whose names start with s.

❖ You can test abbreviations by using them as arguments to the help command.

(gdb) help s

Page 388: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Command Syntax❖ A blank line as input to GDB (typing just RET) means to

repeat the previous command.

❖ Certain commands (for example, run) will not repeat this way; these are commands whose unintentional repetition might cause trouble and which you are unlikely to want to repeat.

❖ The list and x commands, when you repeat them with RET, construct new arguments rather than repeating exactly as typed. This permits easy scanning of source or memory.

Page 389: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Command Syntax❖ GDB can also use RET in another way: to partition lengthy output,

in a way similar to the common utility more. Since it is easy to press one RET too many in this situation, GDB disables command repetition after any command that generates this sort of display.

❖ Any text from a # to the end of the line is a comment; it does nothing. This is useful mainly in command files.

❖ The C-o binding is useful for repeating a complex sequence of commands. This command accepts the current line, like RET, and then fetches the next line relative to the current line from the history for editing.

Page 390: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Command Completion❖ GDB can fill in the rest of a word in a command for you, if there is only one possibility; it

can also show you what the valid possibilities are for the next word in a command, at any time. This works for GDB commands, GDB subcommands, and the names of symbols in your program.

❖ Press the TAB key whenever you want GDB to fill out the rest of a word. If there is only one possibility, GDB fills in the word, and waits for you to finish the command (or press RET to enter it). For example, if you type

(gdb) info bre TAB

❖ GDB fills in the rest of the word ‘breakpoints’, since that is the only info subcommand beginning with ‘bre’:

(gdb) info breakpoints

❖ You can either press RET at this point, to run the info breakpoints command, or backspace and enter something else, if ‘breakpoints’ does not look like the command you expected.

Page 391: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Command Completion❖ If there is more than one possibility for the next word when you press TAB, GDB sounds a bell. You can either

supply more characters and try again, or just press TAB a second time; GDB displays all the possible completions for that word.

❖ For example, you might want to set a breakpoint on a function whose name begins with ‘make_’, but when you type b make_TAB GDB just sounds the bell. Typing TAB again displays all the function names in your program that begin with those characters, for example:(gdb) b make_ TAB

❖ GDB sounds bell; press TAB again, to see:

make_a_section_from_file make_environmake_abs_section make_function_type make_blockvector make_pointer_type make_cleanup make_reference_type make_command make_symbol_completion_list

(gdb) b make_

❖ After displaying the available possibilities, GDB copies your partial input (‘b make_’ in the example) so you can finish the command.

Page 392: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Command Completion❖ If you just want to see the list of alternatives in the first place, you

can press M-? rather than pressing TAB twice.

❖ Sometimes the string you need, while logically a “word”, may contain parentheses or other characters that GDB normally excludes from its notion of a word.

❖ To permit word completion to work in this situation, you may enclose words in ' (single quote marks) in GDB commands.(gdb) b 'bubble( M-?

bubble(double,double) bubble(int,int)

(gdb) b 'bubble(

Page 393: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Command Completion❖ In some cases, GDB can tell that completing a name requires using quotes. When this

happens, GDB inserts the quote for you (while completing as much as it can) if you do not type the quote in the first place:

(gdb) b bub TAB

❖ GDB alters your input line to the following, and rings a bell:(gdb) b 'bubble(

❖ In general, GDB can tell that a quote is needed (and inserts it) if you have not yet started typing the argument list when you ask for completion on an overloaded symbol.

❖ For more information about overloaded functions, google “gdb C++ expressions.”

❖ You can use the following command to disable overload resolution:(gdb) set overload-resolution off

Page 394: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Command Completion❖ When completing in an expression which looks up a field in a struct, class, or union, GDB also tries to limit completions to the field names available in the type of the left-hand-side:(gdb) p stat.M-?sum sumSq

❖ Here is the C++ referenced in the above example:struct stat { double sum; double sumSq;};

Page 395: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Getting Help❖ You can always ask GDB itself for information on its commands,

using the command help. You can use help (abbreviated h) with no arguments to display a short list of named classes of commands:

(gdb) help

❖ You can also provide a command name:❖ (gdb) help print

❖ And finally, you can provide a command class name in order to get information about the individual commands in that command class. A command class is just a grouping of related GDB commands.

Page 396: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

GDB Command ClassesClass Name Descriptionaliases Aliases of other commandsbreakpoints Making program stop at certain pointsdata Examining datafiles Specifying and examining filesinternals Maintenance commandsobscure Obscure featuresrunning Running the programstack Examining the stackstatus Status inqueriessupport Support facilitiestracepoints Tracing program execution without stopping the program

Page 397: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

info and show

❖ In addition to help, you can use the GDB commands info and show to inquire about the state of your program, or the state of GDB itself.

❖ info: This command is for describing the state of your program.

❖ set: You can assign the result of an expression to an environment variable with set.

❖ show: In contrast to info, show is for describing the state of GDB itself. You can change most of the things you can show, by using the related set command.

Page 398: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Running Programs under GDB

❖ When you run a program under GDB, you must first make sure the compiler is including the symbol table in the generated object file.

❖ You may start GDB with its arguments, if any, in an environment of your choice.

❖ If you are doing native debugging, you may redirect your program’s input and output, debug an already running process, or kill a child process.

Page 399: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Starting your Program

❖ Use the run command to start your program under GDB.

❖ You must first specify the program name with an argument to GDB, or by using the file or exec-file commands.

❖ If you are running your program in an execution environment that supports processes, run creates an inferior process and makes that process run your program.

❖ In some environments without processes, run jumps to the start of your program.

Page 400: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Starting your Program❖ The execution of a program is affected by certain information it

receives from its superior.

❖ GDB provides ways to specify this information, which you must do before starting your program. This information may be divided into four categories:

❖ arguments

❖ environment

❖ working directory

❖ standard input and output

Page 401: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Arguments❖ You can specify the arguments to give your program as the arguments of the run

command. (gdb) run 4 8

❖ If the executable being debugged is called sum, then the above command is similar to the following:

$ ./sum 4 8

❖ If a shell is available on your target, the shell is used to pass the arguments. In Unix systems, you can control which shell is used with the SHELL environment variable.

$ export SHELL=/bin/bash

❖ If you do not define SHELL, GDB uses the default shell (/bin/sh).

Page 402: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Environment❖ The environment consists of a set of environment variables and their values.

❖ Environment variables conventionally record such things as your user name, your home directory, your terminal type, and your search path for programs to run.

❖ Usually you set up environment variables with the shell and they are inherited by all the other programs you run.

❖ When debugging, it can be useful to try running your program with a modified environment without having to start GDB over again.

❖ You can use the set environment command to change parts of the environment that affect your program:

(gdb) set environment USER = foo

❖ The above command is similar to the following:$ export USER=foo

Page 403: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Working Directory❖ Each time you start your program with run, it inherits its working directory from the

current working directory of GDB.

❖ The GDB working directory is initially whatever it inherited from its parent process, but you can specify a new working directory in GDB with the cd command.

❖ The GDB working directory also serves as a default for the commands that specify files for GDB to operate on.

❖ cd [directory]: Set the GDB working directory to directory.

❖ pwd: Print the GDB working directory.

❖ It is generally impossible to find the current working directory of the process being debugged (since a program can change its directory during its run). If you work on a system where GDB is configured with the /proc support, you can use the info proc command to find out the current working directory of the debuggee.

Page 404: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Standard Input and Output❖ By default, the program you run under GDB does input and output to the same

terminal that GDB uses. GDB switches the terminal to its own terminal modes to interact with you, but it records the terminal modes your program was using and switches back to them when you continue running your program.

❖ To display information recorded by GDB about the terminal modes your program is using, you can use:

(gdb) info terminal

❖ You can redirect your program’s input and/or output using shell redirection with the run command. For example,

(gdb) run > outfile

starts your program, diverting its output to the file outfile.

Page 405: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

run and start❖ When you issue the run command, your program begins to execute

immediately. If no breakpoints are set, then the program executes to completion.

❖ The name of the main function can vary from language to language.

❖ With C or C++, the main procedure name is always main, but other languages such as Ada do not require a specific name for their main function.

❖ The debugger provides a convenient way to start the execution of the program and to stop at the beginning of the main function, depending on the language used.

❖ The start command does the equivalent of setting a temporary breakpoint at the beginning of the main function and then invoking the run command.

Page 406: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Stopping and Continuing❖ The principal purposes of using a debugger are so that you can stop your program

before it terminates; or so that, if your program runs into trouble, you can investigate and find out why.

❖ Inside GDB, your program may stop for any of several reasons, such as a signal, a breakpoint, or reaching a new line after a GDB command such as step. You may then examine and change variables, set new breakpoints or remove old ones, and then continue execution.

❖ Usually, the messages shown by GDB provide ample explanation of the status of your program—but you can also explicitly request this information at any time using the following command:

(gdb) info program

❖ This display information about the status of your program: whether it is running or not, what process it is, and why it stopped.

Page 407: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Breakpoints❖ A breakpoint makes your program stop whenever a certain point in

the program is reached.

❖ For each breakpoint, you can add conditions to control in finer detail whether your program stops.

❖ You can set breakpoints with the break command and its variants, to specify the place where your program should stop by line number, function name or exact address in the program.(gdb) break main.cpp:11(gdb) b main

❖ The first example places a breakpoint at line 11 in main.cpp. The second example sets a breakpoint at the beginning of the main function.

Page 408: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Setting Breakpoints❖ Breakpoints are set with the break command.

❖ break location: Set a breakpoint at the given location, which can specify a function name, a line number, or an address of an instruction. The breakpoint will stop your program just before it executes any of the code in the specified location.(gdb) b main.cpp:11

❖ break: When called without any arguments, break sets a breakpoint at the next instruction to be executed in the selected stack frame.(gdb) break

Page 409: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Watchpoints❖ A watchpoint is a special breakpoint that stops your program when the value

of an expression changes. ❖ The expression may be a value of a variable, or it could involve values of one or

more variables combined by operators, such as ‘a + b’.

❖ This is sometimes called data breakpoints. You must use the watch command and variants to set watchpoints, but aside from that, you can manage a watchpoint like any other breakpoint: you enable, disable, and delete both breakpoints and watchpoints using the same commands.

(gdb) watch foo

❖ You can arrange to have values from your program displayed automatically whenever GDB stops at a breakpoint.

(gdb) display foo

Page 410: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Catchpoints❖ A catchpoint is another special breakpoint that stops

your program when a certain kind of event occurs, such as the throwing of a C++ exception or the loading of a library. ❖ You use the catch command and variants to set a

catchpoint.

❖ You can manage a catchpoint like any other breakpoint.(gdb) catch exception std::out_of_range(gdb) catch exception unhandled std::out_of_range

Page 411: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Breakpoints

❖ GDB assigns a number to each breakpoint, watchpoint, or catchpoint when you create it.❖ These numbers are successive integers starting with 1.

❖ In many of the commands for controlling various features of breakpoints you use the breakpoint number to say which breakpoint you want to change.

❖ Each breakpoint may be enabled or disabled; if disabled, it has no effect on your program until you enable it again.

Page 412: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Deleting Breakpoints❖ It is often necessary to eliminate a breakpoint, watchpoint, or catchpoint once it

has done its job and you no longer want your program to stop there. This is called deleting the breakpoint. A breakpoint that has been deleted no longer exists; it is forgotten.

❖ With the clear command you can delete breakpoints according to where they are in your program. (gdb) clear(gdb) clear main.cpp:11(gdb) clear some_func

❖ With the delete command you can delete individual breakpoints, watchpoints, or catchpoints by specifying their breakpoint numbers.(gdb) delete 1

Page 413: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Disabling Breakpoints❖ Rather than deleting a breakpoint, watchpoint, or

catchpoint, you might prefer to disable it. ❖ This makes the breakpoint inoperative as if it had been deleted,

but remembers the information on the breakpoint so that you can enable it again later.

❖ You disable and enable breakpoints, watchpoints, and catchpoints with the enable and disable commands, optionally specifying one or more breakpoint numbers as arguments.

❖ Use info break to print a list of all breakpoints, watchpoints, and catchpoints if you do not know which numbers to use.

Page 414: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Continuing and Stepping

❖ Continuing means resuming program execution until your program completes normally.

❖ In contrast, stepping means executing just one more “step” of your program, where “step” may mean either one line of source code, or one machine instruction.

❖ Either when continuing or when stepping, your program may stop even sooner, due to a breakpoint or a signal.

Page 415: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Continuing and Stepping❖ The continue command is used to resume program execution, at the address where your

program last stopped; any breakpoints set at that address are bypassed.(gdb) continue(gdb) c

❖ The step command is used to continue running your program until control reaches a different source line, then stop it and return control to GDB.(gdb) step(gdb) s

❖ The next command is used to continue to the next source line in the current (innermost) stack frame. This is similar to step, but function calls that appear within the line of code are executed without stopping. Execution stops when control reaches a different line of code at the original stack level that was executing when you gave the next command.

(gdb) next(gdb) n

Page 416: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Examining Source Files❖ GDB can print parts of your program’s source, since the

debugging information recorded in the program tells GDB what source files were used to build it. ❖ When your program stops, GDB spontaneously prints the line

where it stopped.

❖ Likewise, when you select a stack frame, GDB prints the line where execution in that frame has stopped. You can print other portions of source files by explicit command.

❖ If you use GDB through its GNU Emacs interface, you may prefer to use Emacs facilities to view source.

Page 417: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Page 418: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Emacs GDB UI

❖ If you’re in Emacs, then GDB can be started by typingM-x gdb

❖ By default, a minimal UI is opened (just the GDB console). To have a prettier UI open up, you can add the following to your ~/.emacs file:

;; better layout when using gdb(setq gdb-many-windows t)

Page 419: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Printing Source Lines

❖ To print lines from a source file, use the list command.

❖ By default, ten lines are printed.

❖ There are several ways to specify what part of the file you want to print.

❖ (gdb) list(gdb) list main.cpp:4(gdb) list main.cpp:main

Page 420: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - C++ and Systems Programming

Editing Source Files❖ To edit the lines in a source file, use the edit command.

❖ The editing program of your choice is invoked with the current line set to the active line in the program.

❖ Alternatively, there are several ways to specify what part of the file you want to print if you want to see other parts of the program:(gdb) edit main.cpp:11(gdb) edit main.cpp:main

❖ You can customize GDB to use any editor you want by setting the environment variable EDITOR before using GDB. For example, to configure GDB to use the emacs editor, you could use these commands with the bash shell:

$ export EDITOR=/usr/bin/emacs

Page 421: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Find Partners

❖ If you don’t have a partner for P2, then try to find one!

Page 422: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

GDB Demo on Thursday

Page 423: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Reminders❖ Project 2 is due MON 2016-10-10 @ 11:55 PM. 

❖ Exam 1 is THU 2016-09-29 @ 6PM in Forestry Resources II 100.

❖ Cheat Sheet: You will are allowed to bring two pages (one standard-sized piece of paper of 8.5 by 11 inches (215.9 mm x 279.4 mm)) of notes that are hand-written to the midterm exam. You will be required to turn in the cheat/note sheet with your exam.

❖ Scheduling Conflicts: If you have another class scheduled at 6PM on 9/29 or a work commitment that causes a time conflict, then please provide verification of the time conflict to your instructor and request a rescheduling of your exam no later than THU 2016-09-22 (TODAY). We will not grant any rescheduling requests for exam 1 after 9/22. Rescheduled exams usually take place the day before or the day after the regularly scheduled exam.

❖ Review day on 9/27.

❖ There is no official lecture on the day of the exam (9/29).

Page 424: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Some More Team Names…❖ Nerf *this

❖ Team Valor

❖ Why ncurses?

❖ HanShotFirst

❖ why c++?

❖ Rolling in the Heap

❖ It's Compile Time

❖ Lady Bugs

❖ Brogrammers

❖ Kyle and Zack

❖ Clicks out for Harambe

❖ Git r done

❖ The Team

❖ char * team_name

❖ School of Rock 2

❖ STACKS ON STACKS ON STACKS

❖ Please Compile

❖ We just want to see how long this time can be...

❖ My Stack Overfloweth

❖ EXIT_SUCESS

❖ Savage Buggers

❖ Harambe died for our cins

❖ @sian

❖ Hoping for a C++

❖ Hoping for a C++

❖ Ultimate Coders

❖ 2b|!2b

❖ Team CodeBreakers

❖ Harambe #NeverForget

❖ TimAndBen.setGrade("Cotterell",1730,'A');

❖ Bacon Strips Bacon Strips Bacon Strips

Page 425: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exam Format❖ (20) Multiple Choice

❖ (20) Short Answer (not essay)

❖ (30) Code Interpretation

❖ (30) Code Writing

Page 426: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Exam 1 Topics❖ Anything we cover in lecture through today (9/22)

❖ Basics of lab-related and project-related material.

❖ Readings:❖ APUE Ch 1—3

❖ DEITEL Ch 1—10, 22.5—22.6

❖ UNIX Tutorial for Beginners - Chapters 0–3

❖ path_resolution(7)

❖ GDB 2–5 (as a supplement to what we cover in class)

Page 427: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

GDB Demo

Page 428: CSCI 1730 — Fall 2016 Systems Programming · Cotterell - CSCI 1730 - Systems Programming Exercises & Programming Assignments Written solutions to exercises are to be submitted in

Cotterell - CSCI 1730 - Systems Programming

Quiz 4