Beginning C/C++ sans objects (That’s French! That’s fancy!

Slides:



Advertisements
Similar presentations
A C++ Crash Course Part II UW Association for Computing Machinery Questions & Feedback.
Advertisements

This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
Object Oriented Programming in C++ Dr. Hammadi Nait-Charif Media School Bournemouth University
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
ITEC 320 C++ Examples.
C ++ Basics by Bindra Shrestha sce.uhcl.edu/shresthab CSCI 3333 Data Structures.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
C++ (intro) Created by Hwansoo Han Edited by Ikjun Yeom.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
A Quick Look at C for C++ Programmers Noah Mendelsohn Tufts University Web: COMP.
Variables and memory addresses
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
Lecture 01a: C++ review Topics: Setting up projects, main program Memory Diagrams Variables / Types (some of) the many-types-of-const's Input / Output.
Gramming An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
An Introduction to C Programming (assuming that you already know Java; this is not an introduction to C++)
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
1 Chapter 12 Classes and Abstraction. 2 Chapter 12 Topics Meaning of an Abstract Data Type Declaring and Using a class Data Type Using Separate Specification.
Lecture 3: Getting Started & Input / Output (I/O)
Hank Childs, University of Oregon
Chapter 12 Classes and Abstraction
C++ Lesson 1.
Intro to Pointers in C CSSE 332 Operating Systems
EGR 2261 Unit 11 Pointers and Dynamic Variables
Chapter 6 CS 3370 – C++ Functions.
Overview 4 major memory segments Key differences from Java stack
UNIT 5 C Pointers.
A bit of C programming Lecture 3 Uli Raich.
Motivation and Overview
Lecture 9 Files, Pointers
Command Line Arguments
An Introduction to C Programming
C++ in 90 minutes.
Pointers and Pointer-Based Strings
Student Book An Introduction
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Instructor: Ioannis A. Vetsikas
Stack Data Structure, Reverse Polish Notation, Homework 7
FILE INPUT OUTPUT Skill Area 315 Part B Materials Prepared by
Overview 4 major memory segments Key differences from Java stack
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Pointers, Dynamic Data, and Reference Types
More About Data Types & Functions
Given the code to the left:
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Programming in C Miscellaneous Topics.
Lab 1 Introduction to C++.
Created by Hwansoo Han Edited by Ikjun Yeom
Programming in C Miscellaneous Topics.
CS150 Introduction to Computer Science 1
Data Structures with C++
Arrays an array of 5 ints is filled with 3,2,4,1,7
Programming Introduction to C++.
Variables & Basic Types
Pointers and Pointer-Based Strings
Pointers and dynamic objects
C Programming - Lecture 5
CS31 Discussion 1H Fall18: week 7
Pointers, Dynamic Data, and Reference Types
SPL – PS1 Introduction to C++.
Presentation transcript:

Beginning C/C++ sans objects (That’s French! That’s fancy! (assuming that you already know Java)

Minimal C program int main ( int argc, char* argv[] ) { //familiar coments return 0; /* comment just like Java */ } What does main look like in Java?

Java’s main public static void main ( String args[] ) { }

Intro to visual C++

Project (is one program, is a folder) concept

Bill’s definition of main is wrong!

C vs. Java types C Java does not init vars (with a few exceptions) bool, char, short, int, long float, double unsigned char unsigned short unsigned int long long long double Java does init vars (specifically objects which are defined to be an instance of a class OR arrays; primitive types are NOT initialized and require initialization) boolean, byte, short, int, long float, double

Basic output in C++ #include <iostream> using namespace std; int main ( int argc, char* argv[] ) { cout << "hello" << endl; int x; cout << "x = " << x << endl; return 0; } Note that we did not initialize x!

Since we did not initialize x . . . We get a compiler warning from VC++. Linux g++ reports nothing unless we use -Wall option. When we run under Windows, an error box appears. But we can ignore the error and program will still run. Under Linux, no error at all.

C/C++ and arrays

C/C++ and arrays int A[] = { 7, 6, 4, 4, 10, 92, -1 }; cout << A[ 0 ] << endl;

C/C++ and arrays int A[7] = { 7, 6, 4, 4, 10, 92, -1 }; cout << A[ 0 ] << endl;

C/C++ and arrays This is OK too: int A[50] = { 7, 6, 4, 4, 10, 92, -1 }; cout << A[ 10 ] << endl; Unspecified values will be initialized with 0.

Tricky int A[ 50 ]; cout << A[ 20 ] << endl; No error or warning at compile or runtime for above! No initialization to zero either! Use int A[ 50 ] = {}; for initialization. Best practice is to always assume no initialization.

No array bounds checking! int B = 20; int A[] = { 10, 11, 12, 13 }; cout << A[ 6 ] << endl; //prints 20 cout << B << endl; //prints 20 A[ 6 ] = 95; cout << B << endl; //B is now 95! //Magic!

No array size! You must keep track of it yourself: const int N = 100; int A[ N ];

As usual, we can pass arrays to functions. static void f1 ( int A[], int n ) { cout << " in f1:" << endl; for (int i = 0; i < n; i++) { cout << A[ i ] << endl; } }. static void f2 ( int* B, int n ) { cout << " in f2:" << endl; for (int i = 0; i < n; i++) { cout << B[ i ] << endl; } int main ( int argc, char* argv[] ) { const int N = 6; int A[ N ] = { 50, 60, 70, 80, 90, 100 }; f1( A, N ); f2( A, N ); return 0;

C++ and dynamically allocated arrays int* b = new int[ 10 ]; cout << b[ 20 ] << endl; delete b; //mandatory b = 0; //good idea No bounds checking.

C/C++ and pointers

C pointers int i = 12; i is a variable. It exists in some memory location. At that memory location is the value of 12.

C pointers int i = 12; i is a variable. It exists in some memory location. At that memory location is the value of 12. What is the size of i (in bytes)?

C pointers int i = 12; i is a variable. It exists in some memory location. At that memory location is the value of 12. What is the size of i (in bytes)? cout << "An int is " << sizeof( int ) << " bytes." << endl; cout << "i = " << i << ", i occupies " << sizeof( i ) << " bytes " << endl;

C pointers int i = 12; i is a variable. It exists in some memory location. At that memory location is the value of 12. What is the size of i (in bytes)? cout << "An int is " << sizeof( int ) << " bytes." << endl; cout << "i = " << i << ", i occupies " << sizeof( i ) << " bytes " << endl; What is the virtual address of i, i.e., where is i in memory?

C pointers Let’s introduce an operator (&) that yields the address of a variable. int i = 12; cout << "the address of i is " << &i << endl;

C pointers How do we declare variables that hold pointers (instead of values)? int i=12, j=52; int* ptr = &i; //ptr points to i ptr = &j; //ptr now points to j

C pointers Derefencing pointers (getting at what they point to): int i = 12; int* iptr = &i; cout << "i = " << i << ", *iptr = " << *iptr << endl; Is *iptr the same as iptr?

C pointers Derefencing pointers (getting at what they point to): int i = 12; int* iptr = &i; *iptr = 52; cout << "i=" << i << "." << endl; //What is i’s value?

C pointers C pointers can be treated as arrays. #define N 100 int ray[ N ]; int* ptr = ray; //same as ptr=&ray[0]

C pointers C pointers can be treated as arrays. #define N 100 int ray[ N ]; int* ptr = ray; //same as ptr=&ray[0] for (int i=0; i<N; i++) { ptr[i] = 0; //same as ray[i] = 0 }

C pointers C pointers can be treated as arrays. #define N 100 int ray[ N ]; int* ptr = ray; //same as ptr=&ray[0] for (int i=0; i<N; i++) { *ptr = 0; //was ptr[i] = 0; ++ptr; }

C pointers C pointers can be treated as arrays. #define N 100 int ray[ N ]; int* ptr = ray; //same as ptr=&ray[0] for (int i=0; i<N; i++) { *ptr++ = 0; //short cut }

C pointers C pointers can be treated as arrays (most of the time). #define N 100 int ray[ N ]; int* ptr = ray; //same as ptr=&ray[0] for (int i=0; i<N; i++) { *ptr++ = 0; } Every time we ++ ptr, how much is added to ptr? 1?

C pointers Common pitfall int* ptr1, ptr2; //what (type) is ptr2?

C pointers Common pitfall int* ptr1, ptr2; This is actually the same as int *ptr1, ptr2; Which means that ptr2 is an int (not an int*)!

C pointers and arrays Common pitfall #define N 100 int ray[ N ]; int* ptr = ray; printf( “%d %d \n”, ray[N], ptr[1000] );

C pointers and arrays Common pitfall #define N 100 int ray[ N ]; int* ptr = ray; printf( “%d %d \n”, ray[N], ptr[1000] );

We can even pass pieces or arrays! static void f2 ( int* B, int n ) { cout << " in f2:" << endl; for (int i = 0; i < n; i++) { cout << B[ i ] << endl; } int main ( int argc, char* argv[] ) { const int N = 6; int A[ N ] = { 50, 60, 70, 80, 90, 100 }; f2( &A[0], N ); f2( &A[3], 3 ); return 0;

So how far can we go with C/C++ pointers? We can even have pointers to functions! insertionSort( A, n ); void (*foo)(int[], int) = insertionSort; (*foo)(A, n);

Basic C++ input

Basic C++ input Like cout (and cerr), cin is predefined as well.

Basic C++ input Simple: int x = 12; cout << "enter a number: "; cin >> x; cout << "you entered " << x << endl;

C++ file I/o

C++ File Output: ofstream Must #include <fstream> at top. ASCII by default. ofstream myfile( "example.txt" ); myfile << "Writing this to a file. \n"; int x = 12; myfile << x << endl; myfile.close();

C++ File Input: ifstream Also #include <fstream> at top. ASCII by default. ifstream in( "example.txt" ); string s; in >> s; cout << "s=" << s << endl; in.close(); Writing this to a file. 12

C++ File Input: ifstream Also #include <fstream> at top. ASCII by default. ifstream in( "example.txt" ); string s; getline( in, s ); cout << "s=" << s << endl; in.close(); Writing this to a file. 12

C++ File Input: ifstream Also #include <fstream> at top. ASCII by default. ifstream in( "example.txt" ); string s; getline( in, s ); cout << "s=" << s << endl; int x; in >> x; cout << "x=" << x << endl; in.close(); Writing this to a file. 12

C++ File Input: ifstream Also #include <fstream> at top. ASCII by default. ifstream in( "example.txt" ); string s; getline( in, s ); cout << "s=" << s << endl; int x; in >> x; cout << "x=" << x << endl; in.close(); Writing this to a file. 12

C++ File Input: ifstream Also #include <fstream> at top. ASCII by default. ifstream in( "example.txt" ); string s; getline( in, s ); cout << "s=" << s << endl; int x; in >> x; cout << "x=" << x << endl; if (in.fail()) cout << “above is bad" << endl; in.close(); Writing this to a file. 12

C++ File Input: ifstream Careful with eof and error handling! ifstream in( "example.txt" ); string s; getline( in, s ); cout << "s=" << s << endl; while (!in.eof()) { int x; in >> x; cout << "x=" << x << endl; if (in.fail()) cout << "above is bad" << endl; } in.close(); Writing this to a file. 12 13

timing

Timing What can we count/time? elapsed time CPU time # of operations

Timing (Windows) 1. elapsed time You must: #include <time.h> #include <math.h> at the top of your program. clock_t start = clock(); double sum = 0; for (int i = 0; i < 1000000; i++) { sum += sin( i ) * cos( i ); } clock_t end = clock(); double elapsed = ((double)end - start) / CLOCKS_PER_SEC; cout << "elapsed time = " << elapsed << " sec" << endl;

Timing (Windows) 2. CPU time You must: #include <Windows.h> at the top of your program. double start = cpuTime(); double sum = 0; for (int i = 0; i < 1000000; i++) { sum += sin( i ) * cos( i ); } double end = cpuTime(); cout << “cpu time = " << (end - start) << endl;

Timing (Windows) 1 or 2. for elapsed or CPU time of fast computations… double start = cpuTime(); for (int i=0; i<100000000; i++) { double sum = 0; for (int i = 0; i < 100; i++) { sum += sin( i ) * cos( i ); } double end = cpuTime(); cout << “cpu time = " << (end - start) << endl;

Timing (Windows) 2. CPU time (cont’d.) help function //based on: // http://stackoverflow.com/questions/19378805/measure-cpu-time-on-windows-using-getprocesstimes static double cpuTime ( void ) { FILETIME createTime, exitTime, kernelTime, userTime; if (GetProcessTimes( GetCurrentProcess(), &createTime, &exitTime, &kernelTime, &userTime ) != -1) { SYSTEMTIME userSystemTime; if (FileTimeToSystemTime( &userTime, &userSystemTime ) != -1) return (double) userSystemTime.wHour * 3600.0 + (double) userSystemTime.wMinute * 60.0 + (double) userSystemTime.wSecond + (double) userSystemTime.wMilliseconds / 1000.0; } return -1;

Timing (Windows, complete) #include <iostream> #include <math.h> #include <time.h> #include <Windows.h> using namespace std; //based on: // http://stackoverflow.com/questions/19378805/measure-cpu-time-on-windows-using-getprocesstimes static double cpuTime ( void ) { FILETIME createTime, exitTime, kernelTime, userTime; if (GetProcessTimes( GetCurrentProcess(), &createTime, &exitTime, &kernelTime, &userTime ) != -1) { SYSTEMTIME userSystemTime; if (FileTimeToSystemTime( &userTime, &userSystemTime ) != -1) return (double) userSystemTime.wHour * 3600.0 + (double) userSystemTime.wMinute * 60.0 + (double) userSystemTime.wSecond + (double) userSystemTime.wMilliseconds / 1000.0; } return -1; int main ( int argc, char* argv[] ) { //mark start time clock_t st = clock(); double start = cpuTime(); //do stuff double sum = 0; for (double d=0; d<10000; d+=0.01) { sum += sin( d ) * cos( d ); } Sleep( 2000 ); //sleep for 2 sec //mark end time double end = cpuTime(); clock_t et = clock(); //calc deltas double cpuTime = end - start; double elapsedTime = ((double)et - st) / CLOCKS_PER_SEC; //report results cout << "cpu time = " << cpuTime << " sec" << endl; cout << "elapsed time = " << elapsedTime << " sec" << endl; return 0;

Timing (generic) 3. # of operations long count = 0; double sum = 0; for (int i = 0; i < 1000000; i++) { sum += sin( i ) * cos( i ); ++count; } cout << "operation count = " << count << endl;

Timing (Linux. Mac?) Use gettimeofday() to get the elapsed time. Use clock() for CPU time (confusing because VC++ uses clock() for elapsed time.

Timing (Linux. Mac?) #include <iostream> #include <math.h> #include <sys/time.h> #include <time.h> #include <unistd.h> using namespace std; int main ( int argc, char* argv[] ) { //mark start time struct timeval startTv; gettimeofday( &startTv, NULL ); clock_t start = clock(); //do stuff double sum = 0; for (double d=0; d<10000; d+=0.01) { sum += sin( d ) + cos( d ); } sleep( 2 ); //sleep for 2 sec //mark end time clock_t end = clock(); struct timeval endTv; gettimeofday( &endTv, NULL ); //calc deltas double cpuTime = ((double)end - start) / CLOCKS_PER_SEC; double st = startTv.tv_sec + (startTv.tv_usec / 1e6); double et = endTv.tv_sec + (endTv.tv_usec / 1e6); double elapsedTime = et - st; //report results cout << "cpu time = " << cpuTime << " sec" << endl; cout << "elapsed time = " << elapsedTime << " sec" << endl; return 0; }

Which version are you timing (Windows)? Debug the Debug version; report times for the Release version.

Which version are you timing (Linux/Mac)? Debug the Debug version; report times for the Release version. Compile with -g for Debug version. Compile with -O3 for Release version.

misc

Strings C++ (not C) provides strings as first-class objects. You must: #include <string> at the top of your program.

Strings string s1 = "hello"; string s2 = "world"; string s3 = s1 + " " + s2; cout << s3 << endl;

Strings (not as “slick” as Java) Compiler error: int x = 12; string s4 = s1 + x + s2; cout << s4 << endl; (Use stringstream instead.)

Random # generator Not the best (see http://www.cplusplus.com/reference/random/ for a better one). You must: #include <time.h> at the top of your program. srand( (unsigned int)time(NULL) ); //one-time init for (int i = 0; i < 10; i++) cout << "random: " << rand() << endl;

C++ classes (do not use at this time) class Simple3D : public DistanceTransform3D { public: //define public members (data) and methods (functions) here … private: protected: };

Handling C/C++ command line arguments argc count/number of arguments argv array of strings (the actual arguments) Java doesn’t have argc. Why? In Java, argv[0] is the first argument. In C/C++, argv[0] is the name of the program/command and argv[1] is the first argument.

Compiling C/C++ programs on Linux (and Mac?) Use which g++ to determine if it’s installed. g++ compiles both C and C++ Always use g++ for C or C++. (Don’t use gcc. It only compiles C and C programs that compile with gcc may not compile with g++.) g++ won’t compile 1978 K&R C code but you shouldn’t be coding in that anyway. File name extensions Always use .cpp for C or C++. (Don’t use .c. It is only for C programs which may compile with gcc but not with g++.) Enter ‘man g++’ for help.

Compiling and running C programs on Linux (and Mac?) g++ command options -g, -O, -O2, -O3 Optimization level – debug to optimized. -c Compile (making a .o file) but don’t link. -o Specify output file name. -l (el=lower case L) Specify link library name.

Example of compiling C programs g++ junk.cpp Compile and link producing a.out. g++ -c junk.cpp Compile (but don’t link) producing junk.o. g++ -o junk.exe junk.o Link junk.o and produce junk.exe. g++ -o junk.exe junk.cpp Compile and link producing junk.exe.

Example of compiling C programs g++ -g -o junk.exe junk.cpp Compile and link producing junk.exe w/ debug information. g++ -O3 -o junk.exe junk.cpp Compile and link producing an optimized version called junk.exe. g++ -O -o fred.exe junk1.cpp junk2.o \ junk3.cpp -lm Compile junk.1pp and junk3.cpp (but not junk2.o) and link producing fred.exe which is somewhat optimized and linked to the math library.

Modular programming in C++

Modularity To facilitate (unit) testing, put your code in files other than the one that contains main. For example, put selectionSort in selectionSort.cpp; put insertionSort in insertionSort.cpp; put your test code in Sort.cpp (or SortTest.cpp or Main.cpp) For OOP, put each object definition in a separate file by the same name as the name of the object.

Modularity //--------------------------------------------------- //file: sortMain.cpp #include extern void selectionSort ( int A[], int n ); extern void insertionSort ( int A[], int n ); using namespace std; int main ( int argc, char* argv[] ) { … } //------------------------------------------------- //file: selectionSort.cpp void selectionSort ( int A[], int n ) { … } //file: insertionSort.cpp void insertionSort ( int A[], int n ) {

Modularity (in VC++) r-click Source Files, Add, New item…

Modularity (Linux/Mac command line) Create 3 separate files: sortMain.cpp, insertionSort.cpp, and selectionSort.cpp. Compile with: g++ -Wall -o sort.exe sortMain.cpp insertionSort.cpp selectionSort.cpp Run with: ./sort.exe

Fitting curves w/ Matlab/Octave Problem: I have a set of data points (that I sampled from some underlying function), and would like to fit them to a second order polynomial. How can I do that?

Fitting curves w/ Matlab/Octave x = [10 100 1000 10000 100000 200000 300000 400000 500000 1000000] y = [1.65e-08 2.19e-07 2.14e-06 2.13e-05 0.0002859 5.797 12.813 22.77 35.56 142.66] plot( x, y ) p = polyfit( x, y, 2 ) x1 = linspace( 0, 1000000 ); y1 = polyval( p, x1 ); figure plot( x, y, 'o' ) hold on plot( x1, y1 ) hold off

Fitting curves w/ Matlab/Octave

Fitting curves w/ Matlab/Octave

End of Beginning C/C++ sans objects