the gamedesigninitiative at cornell university Lecture 6 C++: Basics

Similar documents
the gamedesigninitiative at cornell university Lecture 7 C++ Overview

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

UEE1303(1070) S 12 Object-Oriented Programming in C++

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

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

Lecture 2, September 4

CSE 303: Concepts and Tools for Software Development

Lecture 7: Binding Time and Storage

CE221 Programming in C++ Part 1 Introduction

CS2141 Software Development using C/C++ Compiling a C++ Program

Computer Science II Lecture 1 Introduction and Background

a data type is Types

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

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

CS 220: Introduction to Parallel Computing. Beginning C. Lecture 2

Algorithms and Programming I. Lecture#12 Spring 2015

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

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

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

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

Pointers, Dynamic Data, and Reference Types

C and C++ I. Spring 2014 Carola Wenk

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

C++ Support Classes (Data and Variables)

CS 61C: Great Ideas in Computer Architecture Introduction to C

Reliable C++ development - session 1: From C to C++ (and some C++ features)

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

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

CSI33 Data Structures

CMPT 115. C tutorial for students who took 111 in Java. University of Saskatchewan. Mark G. Eramian, Ian McQuillan CMPT 115 1/32

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

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

Lectures 5-6: Introduction to C

Please refer to the turn-in procedure document on the website for instructions on the turn-in procedure.

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

Separate Compilation Model

CS 11 java track: lecture 1

C for C++ Programmers

C Introduction. Comparison w/ Java, Memory Model, and Pointers

the gamedesigninitiative at cornell university Lecture 10 Memory Management

C++ Programming for Non-C Programmers. Supplement

Final CSE 131B Spring 2004

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2016

Memory Management: The Details

04-19 Discussion Notes

C++ Tutorial AM 225. Dan Fortunato

PIC 10A Objects/Classes

MPATE-GE 2618: C Programming for Music Technology. Unit 4.1

Kurt Schmidt. October 30, 2018

377 Student Guide to C++

Java Bytecode (binary file)

Short Notes of CS201

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

Variables and literals

CS201 - Introduction to Programming Glossary By

CS 231 Data Structures and Algorithms, Fall 2016

Lecture 3: C Programm

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

Starting to Program in C++ (Basics & I/O)

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

CS240: Programming in C. Lecture 2: Overview

ANSI C. Data Analysis in Geophysics Demián D. Gómez November 2013

For instance, we can declare an array of five ints like this: int numbers[5];

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

QUIZ. What are 3 differences between C and C++ const variables?

Introduction to C++ Introduction to C++ 1

CS 177 Recitation. Week 1 Intro to Java

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Implementing an ADT with a Class

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Introducing C++ to Java Programmers

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

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

CSE 303: Concepts and Tools for Software Development

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

Fast Introduction to Object Oriented Programming and C++

AN OVERVIEW OF C++ 1

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

Professor Terje Haukaas University of British Columbia, Vancouver C++ Programming

CS 220: Introduction to Parallel Computing. Arrays. Lecture 4

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

CS24 Week 3 Lecture 1

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

PRINCIPLES OF OPERATING SYSTEMS

Programming Abstractions

CSE 12 Spring 2018 Week One, Lecture Two

Programming in C - Part 2

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2015

CSE 12 Spring 2016 Week One, Lecture Two

Functions and Methods. Questions:

Welcome to MCS 360. content expectations. using g++ input and output streams the namespace std. Euclid s algorithm the while and do-while statements

CSE 333 Lecture 9 - intro to C++

CSE 333 Midterm Exam July 24, Name UW ID#

Functions. Cedric Saule

Chapter 1 Getting Started

CS558 Programming Languages

Transcription:

Lecture 6 C++: Basics

So You Think You Know C++ Most of you are experienced Java programmers Both in 2110 and several upper-level courses If you saw C++, was likely in a systems course Java was based on C++ syntax Marketed as C++ done right Similar with some important differences This Lecture: an overview of differences If you are a C++ expert, will be review 2

So You Think You Know C++ Most of you are experienced Java programmers Both in 2110 and several upper-level courses If you saw C++, was likely in a systems course Java was based on C++ syntax Marketed as C++ done right Similar with some important differences This Lecture: an overview of differences If you are a C++ expert, will be review 3

Comparing Hello World Java /* Comments are single or multiline */ // Everything must be in a class public class HelloWorld { // Application needs a main METHOD public static void main(string arg[]){ C++ /*Comments are single or multiline */ // Nothing is imported by default #include <stdio.h> // Application needs a main FUNCTION int main(){ 4 System.out.println("Hello World"); printf("hello World"); printf("\n"); // Must add newline // Must return something return 0;

Comparing Hello World Java /* Comments are single or multiline */ // Everything must be in a class public class HelloWorld { // Application needs a main METHOD public static void main(string arg[]){ C++ /*Comments are single or multiline */ // Nothing is C-style imported console. by default #include <stdio.h> In CUGL, use // Application CULog needs a instead. main FUNCTION int main(){ 5 System.out.println("Hello World"); printf("hello World"); printf("\n"); // Must add newline // Must return something return 0;

Biggest Difference: Compilation Java Process Compiler CLASS JAVA javac CLASS CLASS Run class file CLASS Loads or classes as it needs m 6

Biggest Difference: Compilation C++ Process Compiler OBJ Linker CPP c++ OBJ c++ EXE OBJ Run executable 7

All Handled by IDE 8

All Handled by IDE Command line work requires a Makefile 9

Makefile Format # Makefile comment (Python style) # Variables. In case we wanted to swap compilers CC=c++ # Main application is first. If you type "make" by itself, you get this. app: main.o helper.o $(CC) -o app main.o helper.o # The object files (pre-linker). Type "make main.o" to get this. main.o: main.cpp main.h helper.h $(CC) -c main.cpp helper.o: helper.cpp helper.h $(CC) -c helper.cpp 10

Makefile Format # Makefile comment (Python style) # Variables. In case we wanted to swap compilers CC=c++ Target # Main application is first. If you type "make" by itself, you get this. app: main.o helper.o $(CC) -o app main.o helper.o # The object files (pre-linker). Type "make main.o" to get this. Evaluates variable main.o: main.cpp main.h helper.h $(CC) -c main.cpp helper.o: helper.cpp helper.h $(CC) -c helper.cpp Dependencies Do if target not re or older than dependencies 11

Makefile Format # Makefile comment (Python style) # Variables. In case we wanted to swap compilers CC=c++ # Main application is first. If you type "make" by itself, you get this. app: main.o helper.o $(CC) -o app main.o helper.o # The object files (pre-linker). Type "make main.o" to get this. main.o: main.cpp main.h helper.h $(CC) -c main.cpp helper.o: helper.cpp helper.h $(CC) -c helper.cpp Linker step Compiler step 12

Separation Requires Header Files Need #include for libs But linker adds libs So what are we including? Function Prototypes Declaration without body Like an interface in Java Prototypes go in.h files Also includes types, classes May have own #includes /* stringfun.h * Recursive string funcs in CS 1110 */ #ifndef_stringfun_h_ #define_stringfun_h_ #include <string> /* True if word a palindrome */ bool ispalindrome(string word); /* True if palindrome ignore case */ bool isloosepalindrome(string word); #endif 13

Separation Requires Header Files Need #include for libs But linker adds libs So what are we including? Function Prototypes Declaration without body Like an interface in Java Prototypes go in.h files Also includes types, classes May have own #includes /* stringfun.h * Recursive string funcs in CS 1110 */ #ifndef_stringfun_h_ #define_stringfun_h_ #include <string> /* True if word a palindrome */ bool ispalindrome(string word); /* True if palindrome ignore case */ bool isloosepalindrome(string word); #endif Prevents inclusion more than once (which is an error) 14

Separation Requires Header Files Need #include for libs But linker adds libs So what are we including? Function Prototypes Declaration without body Like an interface in Java Prototypes go in.h files Also includes types, classes May have own #includes /* stringfun.h * Recursive string funcs in CS 1110 */ #ifndef_stringfun_h_ #define_stringfun_h_ #include <string> /* True if word a palindrome */ bool ispalindrome(string word); /* True if palindrome ignore case */ bool isloosepalindrome(string word); #endif Type not built-in 15

Headers and Namepaces Headers are not packages! Java import is very different Packages prevent collisions C++ has namespaces Define it in header file In-between curly braces Must add prefix when used stringfun::ispalindrome(..) Even in implementation! Unless have using command /* stringfun.h */ #ifndef_stringfun_h_ #define_stringfun_h_ #include <string> namespace stringfun { /* True if word a palindrome */ bool ispalindrome(string word); /* True if palindrome ignore case */ bool isloosepalindrome(string word); #endif 16

Headers and Namepaces Headers are not packages! Java import is very different Packages prevent collisions C++ has namespaces Define it in header file In-between curly braces Must add prefix when used stringfun::ispalindrome(..) Even in implementation! Unless have using command /* stringfun.cpp */ #include "stringfun.h" /* True if word a palindrome */ bool stringfun::ispalindrome(string w) { if (s.size() < 2) { return true; string sub = s.substr(1,s.size()-2); return s[0] == s[s.size()-1] && stringfun::ispalindrome(sub); 17

Headers and Namepaces Headers are not packages! Java import is very different Packages prevent collisions C++ has namespaces Define it in header file In-between curly braces Must add prefix when used stringfun::ispalindrome(..) Even in implementation! Unless have using command /* stringfun.cpp */ #include "stringfun.h using namespace stringfun; /* True if word a palindrome */ bool stringfun::ispalindrome(string w) { if (s.size() < 2) { return true; string sub = s.substr(1,s.size()-2); return s[0] == s[s.size()-1] && ispalindrome(sub); 18

Headers and Namepaces Headers are not packages! Java import is very different Packages prevent collisions C++ has namespaces Define it in header file In-between curly braces Must add prefix when used stringfun::ispalindrome(..) Even in implementation! Unless have using command /* stringfun.cpp */ #include "stringfun.h using namespace stringfun; /* True if word a palindrome */ bool stringfun::ispalindrome(string w) { Prefix here if (s.size() < 2) { return true; Not here string sub = s.substr(1,s.size()-2); return s[0] == s[s.size()-1] && ispalindrome(sub); 19

Pointers vs References Pointer Variable with a * modifier Stores a memory location Can modify as a parameter Must dereference to use Can allocate in heap Reference Variable with a & modifier Refers to anor variable Can modify as a parameter No need to dereference Cannot allocate in heap Java s reference variables are a combination of two 20

Pointers vs References Pointer Variable with a * modifier Stores a memory location Safer! Can modify as a parameter Preferred if do Must dereference not need to use heap Can allocate in heap Reference Variable with a & modifier Refers to anor variable Can modify as a parameter No need to dereference Cannot allocate in heap Java s reference variables are a combination of two 21

When Do We Need Heap? To return a non-primitive Return value is on stack Copied to stack of caller Cannot copy if size variable Important for arrays, objects But objects can cheat 22 0x7ed508??? 0x7ed528 4 0x7ed548 0 0x7ed568 1 0x7ed588 2 0x7ed5a8 3 return int* makearray(int size) { // Array on stack int result[size]; // Initialize contents for(int ii = 0; ii < size; ii++) { result[ii] = ii; return result; // BAD! 0x7ed508 address does not exist 0x7ed548

Allocation and Deallocation Not An Array Basic format: type* var = new type(params); delete var; Example: int* x = new int(4); Point* p = new Point(1,2,3); One you use most Arrays Basic format: type* var = new type[size]; delete[] var; // Different Example: int* array = new int[5]; Point* p = new Point[7]; Forget [] == memory leak 23

Strings are a Big Problem Java string operations allocate to heap allocate s = "The point is ("+x+","+y+")" allocate How do we manage se in C++? For char*, we don t. Operation + is illegal. For string, we can use + but it comes at a cost Idea: Functions to remove string memory worries Formatters like printf and CCLog for direct output Stream buffers to cut down on extra allocations 24

Displaying Strings in C++ C-Style Formatters printf(format,arg1,arg2, ) Substitute into % slots Value after % indicates type Examples: printf("x = %d",3) printf("string is %s","abc") Primarily used for output Logging/debug (CCLog) Very efficient for output C++ Stream Buffers strm << value << value << Easy to chain arguments But exact formatting tricky Example: cout << "x = " << 3 << endl stringstream s << "x = " << 3 Great if you need to return More efficient than + op Can concatenate non-strings 25

How Does Concatenation Work? String operations allocate Each string needs memory String ops are expensive C++11 has optimized a lot Memory may be on stack Almost never new strings Return/parameters copied Will see implications later What does this mean? Simple operations are okay Orwise use stringstream void foo() { string a = "Hello"; // Stack string b("hello"); // Stack // THIS is on heap string c = new String("Hello"); string d = a+" World"; // Stack string e = *c+" World"; // Stack // Copies to next frame in stack return e; // a, b, d, e are deleted // c is still in heap 26

Next Time: Classes and Closures 27