Computer Science Introduction to C++ Haysn Hornbeck

Similar documents
Draft. Chapter 1 Program Structure. 1.1 Introduction. 1.2 The 0s and the 1s. 1.3 Bits and Bytes. 1.4 Representation of Numbers in Memory

Binghamton University. CS-220 Spring X86 Debug. Computer Systems Section 3.11

CSE 351 Section 4 GDB and x86-64 Assembly Hi there! Welcome back to section, we re happy that you re here

The Compilation Process

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

SYSTEMS PROGRAMMING AND COMPUTER ARCHITECTURE Assignment 5: Assembly and C

1. A student is testing an implementation of a C function; when compiled with gcc, the following x86-64 assembly code is produced:

CS356: Discussion #7 Buffer Overflows. Marco Paolieri

Credits and Disclaimers

Motivation was to facilitate development of systems software, especially OS development.

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

Credits and Disclaimers

Areas for growth: I love feedback

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

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

Introduction to C++ Systems Programming

C and Programming Basics

Page 1. Agenda. Programming Languages. C Compilation Process

Function Calls and Stack

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

A brief introduction to C++

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

typedef Labeling<unsigned char,short> LabelingBS; typedef Labeling<unsigned char,short>::regioninfo RegionInfoBS;

Lab 10: Introduction to x86 Assembly

Compiler Design IIIT Kalyani, West Bengal 1. Introduction. Goutam Biswas. Lect 1

What is concurrency? Concurrency. What is parallelism? concurrency vs parallelism. Concurrency: (the illusion of) happening at the same time.

Motivation was to facilitate development of systems software, especially OS development.

Fast Introduction to Object Oriented Programming and C++

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

C Compilation Model. Comp-206 : Introduction to Software Systems Lecture 9. Alexandre Denault Computer Science McGill University Fall 2006

C Programming Review CSC 4320/6320

Roadmap. Java: Assembly language: OS: Machine code: Computer system:

GCC and Assembly language. GCC and Assembly language. Consider an example (dangeous) foo.s

CS 376b Computer Vision

Semantics of C++ Hauptseminar im Wintersemester 2009/10 Templates

Introduction Selected details Live demos. HrwCC. A self-compiling C-compiler. Stefan Huber Christian Rathgeb Stefan Walkner

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

C++ Named Return Value Optimization

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

6.096 Introduction to C++ January (IAP) 2009

CSE 333 Lecture 9 - intro to C++

C++ Tutorial AM 225. Dan Fortunato

Program Translation. text. text. binary. binary. C program (p1.c) Compiler (gcc -S) Asm code (p1.s) Assembler (gcc or as) Object code (p1.

Credits and Disclaimers

C++ Basics. Brian A. Malloy. References Data Expressions Control Structures Functions. Slide 1 of 24. Go Back. Full Screen. Quit.

Introduction to C++ (Extensions to C)

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

Machine/Assembler Language Putting It All Together

Concurrency. Johan Montelius KTH

How Software Executes

Linked List using a Sentinel

Lab 1: First Steps in C++ - Eclipse

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

1 Number Representation(10 points)

Programming at Compile Time. Rainer Grimm Training, Coaching, and Technology Consulting

CSE 303: Concepts and Tools for Software Development

Come and join us at WebLyceum

Princeton University Computer Science 217: Introduction to Programming Systems. Assembly Language: Function Calls

Machine Program: Procedure. Zhaoguo Wang

Essentials for Scientific Computing: Source Code, Compilation and Libraries Day 8

Introduction to Programming using C++

Programming at Compile Time. Rainer Grimm Training, Coaching, and Technology Consulting

CS-220 Spring 2018 Test 2 Version Practice Apr. 23, Name:

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2017 Lecture 7

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

Template Metaprogramming in Finite Element Computations

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CS 261 Fall Machine and Assembly Code. Data Movement and Arithmetic. Mike Lam, Professor

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

Layers of Abstraction CS 3330: C. Compilation Steps. What s in those files? Higher-level language: C. Assembly: X86-64.

University of Washington

CE221 Programming in C++ Part 1 Introduction

The University of Nottingham

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2017 Lecture 12

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Machine Programming 3: Procedures

APPENDIX A : KEYWORDS... 2 APPENDIX B : OPERATORS... 3 APPENDIX C : OPERATOR PRECEDENCE... 4 APPENDIX D : ESCAPE SEQUENCES... 5

CS3157: Advanced Programming. Outline

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Changelog. Assembly (part 1) logistics note: lab due times. last time: C hodgepodge

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

Corrections made in this version not seen in first lecture:

A Tour of the C++ Programming Language

Floating point - summary 1

Buffer Overflow. An Introduction

Layers of Abstraction. CS 3330: More C. printf. Last time

Credits and Disclaimers

CS 2505 Computer Organization I Test 2. Do not start the test until instructed to do so! printed

CS356: Discussion #8 Buffer-Overflow Attacks. Marco Paolieri

Memory and C/C++ modules

GCC : From 2.95 to 3.2

CS429: Computer Organization and Architecture

COMP322 - Introduction to C++

A Tour of the C++ Programming Language

PRINCIPLES OF OPERATING SYSTEMS

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

PROGRAMMING IN C++ KAUSIK DATTA 18-Oct-2017

Transcription:

Computer Science Introduction to C++ Haysn Hornbeck

Housekeeping Online Survey What do you use? How skilled are you? What are you interested in? https://goo.gl/forms/pyiparu6ig4gugxu1 2

Housekeeping Introductory Courses Quick introductions Refresh knowledge Tease full courses? https://goo.gl/forms/pyiparu6ig4gugxu1 3

Housekeeping Intro to Linux Advanced Linux Intro to C++ Code Repositories Pointers and Indirection Designing OO Programs Debugging in Eclipse Memory management https://goo.gl/forms/pyiparu6ig4gugxu1 https://moodle.cpsc.ucalgary.ca/ 4

Housekeeping Materials (CompSci) UofC IT account (see HelpDesk) Remote Login http://www.ucalgary.ca/cpsc/tech/services/remote_access_samba https://goo.gl/forms/pyiparu6ig4gugxu1 5

Housekeeping Materials (not CompSci) Mac OS X Libraries, Various odd places Bootable USB keys https://rufus.akeo.ie/ http://unetbootin.github.io/ Virtual Machines https://virtualboxes.org/images/ https://goo.gl/forms/pyiparu6ig4gugxu1 6

Housekeeping Online Survey https://goo.gl/forms/pyiparu6ig4gugxu1 7

History C 8

History 1966 BCPL https://www.bell-labs.com/usr/dmr/www/bcpl.pdf 9

BCPL GET "LIBHDR" // calculate factorials LET START() = VALOF $( FOR I = 1 TO 5 DO WRITEF("%N! = %I4*N", I, FACT(I)) RESULTIS 0 $) AND FACT(N) = N = 0 -> 1, N * FACT(N - 1) https://en.wikipedia.org/wiki/bcpl#examples 1 0

BCPL 1 1 First to use code blocks Two-step compilation Procedures with parameters and return Only one data type, 16-bit word Pointers

History 1 2 1969 B

B main() { extrn fact, printn, putchar; auto i, r; } i = 1; while(i<6) { printn( fact(i), 10 ); putchar( *n ); /* *n = newline */ i =+ 1; } printn(n,b) { extrn putchar; auto a; } if(a=n/b) /* assign and check */ printn(a, b); putchar(n%b + '0'); /* exploit ASCII encoding */ fact(n) { } if(n<2) return 1; else return n * fact(n-1); https://www.bell-labs.com/usr/dmr/www/kbman.html 1 3

History 1 4 1972 Unix on the PDP-11

History 1 5 1972 C

C 1 6 #include <stdio.h> int fact( n ) { } if (n<2) return 1; else return n * fact(n-1); int main( int argc, char* argv[] ) { int i = 1; while (i<6) printf( %f\n, fact(i++) ); } return 0;

C 1 7 Multiple fundamental data types Structures Static types, weak enforcement Weak array support Multi-step compilation

Multiple Data Types 1 8 bool char short int long long long unsigned char unsigned short unsigned int unsigned long unsigned long long float double

Structures // by tagname struct point { }; float x; float y; struct point p; // tagname alias typedef struct point d2; // by alias typedef struct { float x; float y; } point; point p; d2 p; 1 9

Static Types, Weak Enforcement 2 0 // all these are valid long first = 17592186044416; int second = 16777216; char third = first + second; int fourth = 4.0134; float pi = 3.14159274; int fifth = *(int*)π

Static Types, Weak Enforcement 2 1 // all these are valid long first = 17592186044416; int second = 16777216; char third = first + second; // 0 int fourth = 4.0134; // 4 float pi = 3.14159274; int fifth = *(int*)π // 1078530011?!

Weak Array Support 2 2 int array[5]; for (int it = 0; it < 11; it++) array[it] = it; // this works?!

Weak Array Support 2 3 int array[5]; for (int it = 0; it < 11; it++) array[it] = it; // this works?! 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 char** argv int argc 16 Arra y[0] Array[1] Array[2] Arra y[3] 32 Arra y[4 ] float pi 4 8 int fifth int fourth char third int second 64 long first

Multi-step Compilation Preprocessor (insert files, expand macros) Compile (convert to assembly code) Assemble (convert to machine code) Link (combine parts and libraries) 2 4

Preprocessor 2 5 shared.h stdio.h stdio.h shared.h main.cpp main.cpp

Compile 2 6 stdio.h shared.h main.asm main.cpp

Assembly Language main:.lfb0:.l3:.file "test.c".text.globl main.type main, @function.cfi_startproc pushq %rbp.cfi_def_cfa_offset 16.cfi_offset 6, -16 movq %rsp, %rbp.cfi_def_cfa_register 6 movl %edi, -68(%rbp) movq %rsi, -80(%rbp) movabsq $17592186044416, %rax movq %rax, -16(%rbp) movl $16777216, -20(%rbp) movl -20(%rbp), %eax movl %eax, %edx movq -16(%rbp), %rax addl %edx, %eax movb %al, -21(%rbp) movl $4, -28(%rbp) movss.lc0(%rip), %xmm0 movss %xmm0, -36(%rbp) leaq -36(%rbp), %rax movl (%rax), %eax movl %eax, -32(%rbp) movl $0, -4(%rbp) jmp.l2 movl cltq movl movl addl -4(%rbp), %eax -4(%rbp), %edx %edx, -64(%rbp,%rax,4) $1, -4(%rbp).L2:.LFE0:.LC0: cmpl $10, -4(%rbp) jle.l3 movl $0, %eax popq %rbp.cfi_def_cfa 7, 8 ret.cfi_endproc.size main,.-main.section.rodata.align 4.long 1078530011.ident "GCC: (Debian 6.2.1-5) 6.2.1 20161124".section.note.GNU-stack,"",@progbits 2 7

Assemble 2 8 main.asm main.bin

Link 2 9 stdio.bin stdio.bin main.bin main.bin processing.bin processing.bin

Why C Stinks Pointers 3 0 Poor organization Side effects galore Trust the coder

History 3 1 1967 Simula 67

Simula 67 3 2 Class Rectangle (Width, Height); Real Width, Height;! Class with two parameters; Begin Real Area, Perimeter;! Attributes; Procedure Update;! Methods (Can be Virtual); Begin Area := Width * Height; Perimeter := 2*(Width + Height) End of Update; Boolean Procedure IsSquare; IsSquare := Width=Height; Update;! Life of rectangle started at creation; OutText("Rectangle created: "); OutFix(Width,2,6); OutFix(Height,2,6); OutImage End of Rectangle;

History 3 3 1979 C with Classes

History 3 4 1983 C++

History 3 5 1989 C++ 2.0

History 3 6 1998 ISO/IEC 14882:1998 (C++98)

History 3 7 1998 2003 2011 2014 2017

Demo Code 3 8

Demo Code 3 9 (x x o ) 2 +( y y o ) 2 = r π = circumference diameter

Demo Code 4 0 x x o + y y o = r π = circumference diameter

Demo Code 4 1 x x o + y y o = r π = 4

Demo Code 4 2 3 (x x o ) 3 +( y y o ) 3 = r π 3.259767993

Demo Code 4 3 https://en.wikipedia.org/wiki/lp_space#the_p-norm_in_finite_dimensions p (x x o ) p +( y y o ) p = r π =?

Classes, Attributes, Methods,... 4 4 class PiEstimator { private: CircleGenerator cg; set<point> points; public: PiEstimator( fp p ); fp getp() { return cg.getp(); } void setp( fp p ); // used to create points // the points that make up our arc // estimate Pi via a lot of "random" points fp estimateviaflood( ulong count ); // estimate Pi via distance segmentation fp estimateviasegment( fp maxdist ); }; // PiEstimator

Typedef 4 5 typedef unsigned long ulong; typedef double fp;

Inheritence, Virtual Functions 4 6 class DistanceMetric { public: static virtual fp distance( const& Point, const& Point ); }; // DistanceMetric class EuclideanDistance : public DistanceMetric { public: static fp distance( const& Point a, const& Point b ) { }; } return sqrt( (a.getx() - b.getx())*(a.getx() - b.getx()) + (a.gety() - b.gety())*(a.gety() - b.gety()) );

Operator Overloading 4 7 class Point { private: fp x; fp y; public: /*... */ // the coordinates of this point in 2D space // so we're organized in set bool operator<( const Point& a ) const; // to make some operations easier Point operator+( const Point& a ) const; Point operator-( const Point& a ) const; Point operator*( const fp& a ); Point power( const fp& a ); Point absolute(); }; // Point

Operator Overloading class Point { private: fp x; fp y; // the coordinates of this point in 2D space public: /*... */ // so we're organized in set bool operator<( const Point& a ) const; // to make some operations easier Point operator+( const Point& a ) const; Point operator-( const Point& a ) const; Point operator*( const fp& a ); Point power( const fp& a ); Point absolute(); }; // Point Point a; Point b; Point c = a b; // Point c( a.getx() - b.getx(), a.gety() - b.gety() ); 4 8

Inheritence, Virtual Functions 4 9 class DistanceMetric { public: static virtual fp distance( const& Point, const& Point ); }; // DistanceMetric class EuclideanDistance : public DistanceMetric { public: static fp distance( const& Point a, const& Point b ) { // return sqrt( (a.getx() - b.getx())*(a.getx() - b.getx()) + // (a.gety() - b.gety())*(a.gety() - b.gety()) ); }; } return ((a b).dot(a b)).sqrt();

Input / Output 5 0 #include <stdio.h> printf( For precision %f and exponent %f, Pi ~= %.15f\n, precision, exponent, pe.estimateviasegment( precision ) ); using std::cout; using std::endl; using std::setprecision; #include <iostream> std::cout << "For precision " << precision << " and exponent " << exponent << ", Pi ~= " << std::setprecision(15) << pe.estimateviasegment( precision ) << std::endl;

Namespaces 5 1 #include <stdio.h> printf( For precision %f and exponent %f, Pi ~= %.15f\n, precision, exponent, pe.estimateviasegment( precision ) ); #include <iostream> using std::cout; using std::endl; using std::setprecision; cout << "For precision " << precision << " and exponent " << exponent << ", Pi ~= " << setprecision(15) << pe.estimateviasegment( precision ) << endl;

Namespaces 5 2 #include <stdio.h> printf( For precision %f and exponent %f, Pi ~= %.15f\n, precision, exponent, pe.estimateviasegment( precision ) ); #include <iostream> using std::cout; using std::endl; using std::setprecision; cout << "For precision " << precision << " and exponent " << exponent << ", Pi ~= " << setprecision(15) << pe.estimateviasegment( precision ) << endl; // Point Point::operator+( const Point& a ) const;

Namespaces 5 3 // creating a namespace namespace mypackage { class myclass { public: void dosomething(); }; } // importing from a namespace using mypackage::myclass; myclass.dosomething();

Namespaces 5 4 Point Point::pow( const fp& s ) { // doesn t compile } return Point( pow(x,s), pow(y,s) ); Point Point::power( const fp& s ) { } return Point( pow(x,s), pow(y,s) );

Templates 5 5 class PairPoints { private: Point a; Point b; public: Point first() { return a; } Point second() { return b; } };

Templates 5 6 template <class T>; class Pair { private: T a; T b; public: T first() { return a; } T second() { return b; } }; Pair<Point> ray;

Template Specialization 5 7 template <class T>; class Pair { // assume it s a pass-by-value bool lessthan( const& T rhs ) { return *this < rhs; } //... template <>; class Pair<T*> { // know we have a reference bool lessthan( const& T rhs ) { return **this < *rhs; } //...

Standard Template Library 5 8 Vector - Dynamic array List Set Map Queue Array - Linked list - Ordered list - Key -> value - First in, First out - Fixed-size array

Operator Overloading 5 9 class Point { private: fp x; fp y; public: /*... */ // the coordinates of this point in 2D space // so we're organized in set bool operator<( const Point& a ) const; // to make some operations easier Point operator+( const Point& a ) const; Point operator-( const Point& a ) const; Point operator*( const fp& a ); Point power( const fp& a ); Point absolute(); }; // Point

Memory Management 6 0 // C Point* point = (Point*) malloc( sizeof(point) ); Point* array = (Point*) malloc( sizeof(point) * count ); free(point); free(array); // C++ Point* point = new Point(); Point* array = new Point[3]; std::vector<point> better; delete point; delete[] array; // quite important!

But... 6 1 C++ = C with some added syntactic sugar

C++ = C 6 2 All C operators work main function still around Ditto pointers Preprocessor and garbage dependency handling Compile-time enforcement Permissive casting

C++ = C 6 3 30+ years of development More libraries than any other language Interfaces to other languages Ported everywhere The Boost libraries

6 4 Lab Challenges http://pages.cpsc.ucalgary.ca/~hhornbec/moodle/cpp_intro/

G++ (GNU C compiler) -o [file] -g -ggdb -O[number] -I [directory] -l [file] The file to output to. Add debugging symbols. Add debugging symbols for GDB. Optimize the code, to varying levels. [0-3] Search for header files in this directory, too. Link in this library, too. http://pages.cpsc.ucalgary.ca/~hhornbec/moodle/cpp_intro/ 6 5