Download presentation
Presentation is loading. Please wait.
Published byDoddy Darmali Modified over 6 years ago
1
Beginning C/C++ sans objects (That’s French! That’s fancy!
(assuming that you already know Java)
2
Minimal C program int main ( int argc, char* argv[] ) {
//familiar coments return 0; /* comment just like Java */ } What does main look like in Java?
3
Java’s main public static void main ( String args[] ) { }
4
Intro to visual C++
5
Project (is one program, is a folder) concept
8
Bill’s definition of main is wrong!
10
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
11
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!
12
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.
14
C/C++ and arrays
15
C/C++ and arrays int A[] = { 7, 6, 4, 4, 10, 92, -1 }; cout << A[ 0 ] << endl;
16
C/C++ and arrays int A[7] = { 7, 6, 4, 4, 10, 92, -1 }; cout << A[ 0 ] << endl;
17
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.
18
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.
19
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!
20
No array size! You must keep track of it yourself: const int N = 100;
int A[ N ];
21
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;
22
C++ and dynamically allocated arrays
int* b = new int[ 10 ]; cout << b[ 20 ] << endl; delete b; //mandatory b = 0; //good idea No bounds checking.
23
C/C++ and pointers
24
C pointers int i = 12; i is a variable. It exists in some memory location. At that memory location is the value of 12.
25
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)?
26
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;
27
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?
28
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;
29
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
30
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?
31
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?
32
C pointers C pointers can be treated as arrays. #define N 100
int ray[ N ]; int* ptr = ray; //same as ptr=&ray[0]
33
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 }
34
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; }
35
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 }
36
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?
37
C pointers Common pitfall int* ptr1, ptr2; //what (type) is ptr2?
38
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*)!
39
C pointers and arrays Common pitfall #define N 100 int ray[ N ];
int* ptr = ray; printf( “%d %d \n”, ray[N], ptr[1000] );
40
C pointers and arrays Common pitfall #define N 100 int ray[ N ];
int* ptr = ray; printf( “%d %d \n”, ray[N], ptr[1000] );
41
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;
42
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);
43
Basic C++ input
44
Basic C++ input Like cout (and cerr), cin is predefined as well.
45
Basic C++ input Simple: int x = 12; cout << "enter a number: "; cin >> x; cout << "you entered " << x << endl;
46
C++ file I/o
47
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();
48
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
49
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
50
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
51
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
52
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
53
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
54
timing
55
Timing What can we count/time? elapsed time CPU time # of operations
56
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 < ; i++) { sum += sin( i ) * cos( i ); } clock_t end = clock(); double elapsed = ((double)end - start) / CLOCKS_PER_SEC; cout << "elapsed time = " << elapsed << " sec" << endl;
57
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 < ; i++) { sum += sin( i ) * cos( i ); } double end = cpuTime(); cout << “cpu time = " << (end - start) << endl;
58
Timing (Windows) 1 or 2. for elapsed or CPU time of fast computations…
double start = cpuTime(); for (int i=0; i< ; 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;
59
Timing (Windows) 2. CPU time (cont’d.) help function //based on:
// 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 * (double) userSystemTime.wMinute * (double) userSystemTime.wSecond + (double) userSystemTime.wMilliseconds / ; } return -1;
60
Timing (Windows, complete)
#include <iostream> #include <math.h> #include <time.h> #include <Windows.h> using namespace std; //based on: // 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 * (double) userSystemTime.wMinute * (double) userSystemTime.wSecond + (double) userSystemTime.wMilliseconds / ; } 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;
61
Timing (generic) 3. # of operations long count = 0; double sum = 0;
for (int i = 0; i < ; i++) { sum += sin( i ) * cos( i ); ++count; } cout << "operation count = " << count << endl;
62
Timing (Linux. Mac?) Use gettimeofday() to get the elapsed time.
Use clock() for CPU time (confusing because VC++ uses clock() for elapsed time.
63
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; }
64
Which version are you timing (Windows)?
Debug the Debug version; report times for the Release version.
65
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.
66
misc
67
Strings C++ (not C) provides strings as first-class objects. You must:
#include <string> at the top of your program.
68
Strings string s1 = "hello"; string s2 = "world"; string s3 = s1 + " " + s2; cout << s3 << endl;
69
Strings (not as “slick” as Java)
Compiler error: int x = 12; string s4 = s1 + x + s2; cout << s4 << endl; (Use stringstream instead.)
70
Random # generator Not the best (see 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;
71
C++ classes (do not use at this time)
class Simple3D : public DistanceTransform3D { public: //define public members (data) and methods (functions) here … private: protected: };
72
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.
73
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.
74
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.
75
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.
76
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.
77
Modular programming in C++
78
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.
79
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 ) {
80
Modularity (in VC++) r-click Source Files, Add, New item…
81
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
82
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?
83
Fitting curves w/ Matlab/Octave
x = [ ] y = [1.65e e e e ] plot( x, y ) p = polyfit( x, y, 2 ) x1 = linspace( 0, ); y1 = polyval( p, x1 ); figure plot( x, y, 'o' ) hold on plot( x1, y1 ) hold off
84
Fitting curves w/ Matlab/Octave
85
Fitting curves w/ Matlab/Octave
86
End of Beginning C/C++ sans objects
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.