lecture5 - CIS 450 Computer Architecture and Organization...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CIS 450 Computer Architecture and Organization Lecture 5: C/C++ Crash Course Mitch Neilsen [email protected] 219D Nichols Hall Topics Linux Operating System Basic Commands Editors C/C++ Programming Languages 2 Linux and Unix Commands man <command> - manual pages = help on <command> ls directory listing = folder listing ps process status mkdir make a directory cp copy a file, directory, or file(s) mv move a file, directory, or file(s) rm remove a file, directory, or file(s) clear clear the input screen cat concatenate files together more or less display output one page at a time head or tail display first or last 10 lines of a file grep GNU regular expression parser look for patterns 3 C/C++ Compilation Process Preprocesser Resolves #define, #include preprocessor directives. Source code (text) .c .h .c .h Compiler Preprocessor C/C++ code (text) Libraries Translates code to Machine Language. It outputs an "object file." This code is not executable. Compiler Linker Linker Takes object files and resolves references to functions and variables in different files. Object code (binary) Native Executable (binary) .exe or .out 4 Declarations - (bad) Example What is wrong with the following code? Will it compile in C? in C++? int main(void) { int result; ... Hint: It has to do with the declaration and use of add. } result = add(20, 3); ... return 0; int add(int a, int b) { return a + b; } 5 Declaration Regions Corrected Code 1 (local prototype) int main(void) { int result; int add(int,int); ... result = add(20, 3); ... return 0; } int add(int a, int b) { return a + b; } ... 6 } ... } int add(int a, int b) { return a + b; add is declared in the shaded regions Corrected Code 2 (global prototype) int add(int,int); int main(void) { int result; ... result = add(20, 3); ... return 0; #define #define Tag Substitution Replaces all following occurrences of Tag with Substitution The Substitution may be the empty string Does not replace Tag if it is inside quotation marks #define Tag(x,y,z) Substitution Creates a Function-like macro Tag The Substitution may refer to the parameters x, y, or z Only items of the form Tag(x,y,z) will be replaced (Just plain Tag will be ignored) #define MAX_SIZE 80 #define GET_FIELD(a,b) a->b int a[MAX_SIZE]; GET_FIELD(point, xCoord); GET_FIELD("lalala", f03j?); 7 cpp int a[80]; point->xCoord "lalala"->f03j? Header Files Common Usages: Creates an informal module interface (No relation to Java interfaces) Provides documentation Each module usually has a header file Often include the following: function prototypes struct and class declarations typedefs global variable declarations lots of (high-level) comments Abstracts code for optimization (less common) 8 #include #include essentially copies and pastes the contents of the given file into the current file There are two forms of #include They differ in the order in which directories are search for the given file The search order is implementation defined Here is the general pattern for different compilers: #include <filename> Searches the "include path," then the current directory #include "filename" Searches the current directory, then the "include path" 9 Header Guards Header guards are a common C/C++ idiom Wrap each header file with the lines: #ifndef FILENAME_H #define FILENAME_H <header file body here> #endif /* FILENAME_H */ There is almost no reason to put things outside of header guards 10 Header File point2d.h #ifndef POINT2D_H #define POINT2D_H struct Point2D { int x; int y; }; typedef struct Point2D Point2D; /* returns the result of the vector addition of * a and b. */ Point2D add(Point2D *a, Point2D *b); /* returns the result of the vector subtraction of * b from a */ Point2D sub(Point2D *a, Point2D *b); #endif /* POINT2D_H */ 11 Classes Roots come from C-style structs Fairly similar to Java classes in concept. Used to group related data and functions. Can be used to write OO code class Queue { public: Queue(); void enqueue(int n); int dequeue(); ~Queue(); private: int numElements; int capacity; int *queueData; }; 12 Basic class Syntax Declaring a class without inheritance Declaring a class: class [optional name] { [access modifier] <type> member1; <type> member2; public: [access modifier] <type> member3; <type> member4; ... } [instance list]; y); int getX(); int getY(); } p1(2,3); Point2D p2(1,3); Point2D *p; 13 Point2D(int x, int Example: class Point2D{ private: int x; int y; Declaring and Defining Methods /* point2d.h */ #ifndef POINT2D_H #define POINT2D_H Point2D::Point2D(int a, int b){ class Point2D{ private: int x; int y; public: Point2D(int x, int y); int getX(); int getY(); }; #endif /* POINT2D_H */ 14 } int Point2D::getY(){ return y; int Point2D::getX(){ return x; } } x = a; y = b; /* point2d.cc */ #include "point2d.h" Classes form a closed namespace Using Point2D #include <cstdio> #include "point2d.h" int main() { Point2D *p = new Point2D(3,4); printf("point: (%d,%d)\n",p->getX(),p->getY()); delete p; p = NULL; return 0; } 15 Constructors Constructors are functions that get called when a class is instantiated Constructors have the same name as their class Constructors may not pass off control to another constructor A default (zero argument) constructor is provided when no other constructors are declared Constructors may invoke the constructors of their super class, and of their member variables via member-wise initialization. 16 Destructors Destructors are called when an object is destroyed; e.g., when an instantiated class is deallocated. Destructors are have no return type and have the same name as their class with a tilde `~' prepended. If no destructor is given, a trivial destructor, which calls the destructor for all elements is given. 17 Inheritance Inheritance is specified by a : and a list of access specifiers + class names in the class declaration class Point2D{ private: int x; int y; public: Point2D(int a, int int getX(); int getY(); }; }; b); public: ColorPoint2D(int x, int y, int color); int getColor(); { private: int color; class ColorPoint2D : public Point2D 18 Inheritance (cont.) Base classes can be public, protected, or private In public inheritance, all public and protected members are inherited In protected inheritance, all public members from the base class become protected In private inheritance, all public and protected members become private Java only has public inheritance You can call any ancestor's class method using the scope resolution operator (::) 19 Dynamic Memory Dynamically sized memory in C and C++ must be manually managed Dynamic memory is not necessarily much slower than static memory All allocated memory must be freed Do not free memory twice (double free) Manual memory management allows for finer grained control of your program 20 new, delete, delete[ ] The new operator allocates new memory, initializes it and returns a pointer to it. The delete operator deallocates memory allocated by new If you allocate a new array, you must delete it with delete and not delete Used in C++ Example: Point2D *p = new Point2D(3,4); delete p; p = NULL; int *ar = new int[50]; delete ar; ar = NULL; Improper use of delete and delete[ ] will cause undefined behavior! 21 malloc, calloc, realloc, free These are C memory management functions Do not mix them with the C++ ones! (that is, don't try to delete memory from malloc, etc.) These functions return void* (pointers to anything) They are not type safe They do not call initializers for the memory There is no realloc equivalent for C++ Some low-level memory management may be faster with these functions, but don't bank on that 22 Arrays <ArrayType> arrayName[ numElements ] Arrays are contiguous memory locations, and its name refers only to the address of the first element Indexing into an array is the same as adding an offset to the address of the first element When declaring an array, its size must be known at compile-time myArray[5] myArray[4] myArray[3] myArray[2] myArray[1] myArray[0] or myArray 23 Arrays as function parameters <ReturnType> funcName( ArrayType arrName[ ] ) int sumOfArray( int values, int numValues ) Arrays are not passed by copying all elements in the array. Instead, the address of the first element is passed to the function. Note how array parameters and non-parameter arrays behave identically 24 Pointers: vocabulary A pointer is a variable that contains addresses of other variables Accessing the data at the contained address is called "dereferencing a pointer" or "following a pointer" x (4104) y (4100) n (4096) int x; int *y; int n; y = &n; *y = 7; 4096 7 25 Pointer Syntax Declaring Pointers Declaring a pointer: <Type> *ptrName; ptrName = a variable that contains the address of something of type <Type> For example: int *nPtr1, *nPtr2; void aFunc(int aParam, int *ptrParam); Using Pointers Dereferencing a pointer: *ptrName = go to the address contained in the variable ptrName Getting the address of a variable: &aVar = get the address of aVar For example: aFunc(myInt, &anotherInt); anInt = *myPtr * 4; *myPtr = 100; 26 Pointers: Putting it all together Box Diagrams The code "p's type is int pointer. q's type is int." Memory Layout p contains the address of an int. q contains an int. Go to the address that p contains, and place a 5 there. p (8200) p q 5 q (8196) 5 8196 int *p; int q; "Assign 5 to where p points (which is q)." p = &q *p = 5; 27 Pointer Arithmetic Pointers are numbers, so you can do math on them! int * p = &a; p (8200) b (8196) a (8192) *p = 200; p (8200) b (8196) a (8192) *(p+1) = 300; p (8200) b (8196) a (8192) 8192 9 16 8192 9 200 8192 300 200 Pointer p refers to an int, so adding 1 to p increments the address by the size of one int. The C/C++ expression for this is sizeof(int) 28 Pointers and Arrays Pointers and arrays are (almost) interchangeable Given: int myArray[5]; int * p = myArray; myArray[4] (9000) myArray[3] (8196) myArray[2] (8192) myArray[1] (8188) myArray[0] (8184) p (8180) These are equivalent: 29 *p myArray[0] *(p+0) *myArray p[0] 0[p] 8184 Function Pointers <ReturnType> (*ptrName)(arg type list ); Functions are pieces of code in memory Pointers can point to functions. Notice that the name of the function appears in the middle of the statement! Unlike variable pointers, you do not have to dereference a function pointer. Function pointers are useful! 30 Function Pointers - example void foo(int i, char b); void bar(int i, char b); int main(void) { void (*p)(int,char); p = foo; p(1, `c'); // equivalent to foo(1, 'c'); p = bar; p(2, `b'); // equivalent to bar(2, `b'); (*p)(2, `b'); // Exactly the same return 0; } 31 C-style struct A struct is used to group related data items struct student { int id; char name[80]; }; To the programmer id and name are now related struct student creates a convenient grouping It is optional whether you name a struct; e.g., student. To the compiler id and name have a fixed ordering (not offset) in memory struct student is a first-class type that can be passed to functions 32 struct Syntax Declaring a Struct Declaring a struct: struct [optional name] { <type> field1; <type> field2; ... } [instance list]; Examples: struct Foo { int field1; char field2; } foo,*foo_ptr; Accessing a field in a struct pointer: struct Foo foo2; struct { int a; } blah; 33 (*foo_ptr).field1; foo_ptr->field1; Access struct fields Accessing a field in a struct: foo.field1; - gets field1 from the instance foo of struct Foo Pointers syntax and structs The * has lower precedence than the `.' : Example: *foo_ptr.field1; which won't compile! means *(foo_ptr.field1); Typedef typedef is used to create an alias to a type typedef unsigned char byte; unsigned char mybyte; byte mybyte; byte now represents an unsigned char Both definitions of mybyte are equivalent to the compiler. The second definition is preferred as it gives more info 34 Typedefs structs/enums/unions People often make a typedef of an anonymous struct or enum typedef struct { int id; char name[80]; } Student; Student st; struct Student { int id; char name[80]; }; struct Student st; These are almost the same. However, anonymous structs cannot refer to themselves. 35 struct List { int data; struct List *next; }; I/O C-style C-style I/O is an acquired taste. Learn to like it. Basic functions: printf, scanf, fprintf, fscanf, sprintf, sscanf, etc. gets, puts, getc, putc, getchar read, write, fread, fwrite We will cover the basics of the "formated" family of functions (printf, scanf, etc). For the others, read the man pages in Unix. 36 printf printf(char *format_string, ...); fprintf(FILE*, char *format_string, ...); snprintf(char* buf, size_t n, char *format_string, ...); In C, all devices are treated like files Three standard files are: stdin Often the keyboard stdout Often the text console stderr Often the text console printf(....) is fprintf(stdout, ....) The format string is a pattern for the output; it describes how to display the arguments to printf. Snprintf write to the string "buf". The variable n specifies the size of the buffer. printf returns the number of characters written 37 format string Format strings are normal strings with embedded "conversion specifications" which are placeholders for arguments Conversion specifications are a `%' and a letter with an optional set of arguments in between the `%' and letter. To print a `%', you need to write `%%' Example: printf("Here is a number: %d\n", 10); %d is the conversion specification for signed integers. 38 Conversion Specifications Conversion specifications tell how to translate a data value into a string Conversion Specifications: %d, %i -- signed integer %u -- unsigned integer %f -- floating point number %c -- character %s -- string %x -- hexadecimal value %p -- pointer Options: l -- long (32-bit value) ll -- long long (64-bit value) n -- field width of n digits .n -- precision of n digits 0 -- fill unused field with 0s 39 I/O C++-style C++-style IO is easier for simple stuff Basic classes: iostream (cout, cin, cerr) ostringstream, istringstream cout << "Hello World!" << endll; cout << "Boo! " << 10 << `c' << endl; cerr << "Here's the error stream" << endl; int n; cin >> n; char ch; cin >> ch; 40 I/O C++-style continued... ...but harder for complex stuff printf("%.3f rounded to 2 decimals is %.2f\n", 2.325, 2.325); ...becomes... cout << setprecision(3) << 2.325 << " rounded to 2 decimals is " << setprecision(2) << 2.325 << endl; 41 Global Variables Global Variables are not evil! Allocated at program start. Deallocated at program end. By default, initialized to bit-wise zero (do not depend on this). Need to understand modifiers: extern, static, and const to use properly. Need to understand linking to use properly. 42 Global Variables - Gotcha What is wrong with this code? /* util.c */ /* test.c */ int g_numCalls = 0; void someFunc(void) { fprintf(stderr, "Num Calls to %s: %d\n", __func__, g_numCalls); ... } someFunc(); someFunc(); ... } int main(void) { fprintf(stderr, "Num Calls to %s: %d\n", __func__, g_numCalls); void someFunc(void); int g_numCalls = 0; compile line: gcc -Wall -ansi util.c test.c -o test 43 static static has 3 very separate meanings On a global variable or a function static int g_someGlobalVariable; static void myFunction(void); Tells the linker not to export the variable or function. Essentially makes the identifier "file scope," as the linker will not use it fulfill dependencies from other files. On a local (function) variable void someFunc(void) { static int array[4000]; } Places the variable off the stack. This has the side-effect that it retains it value across calls. It is often used when a variable is too large to be put on the stack. On a class member (covered when we discuss classes) 44 Globals Variables - Gotcha (fixed) /* util.c */ Static to the rescue!!!!! /* test.c */ void someFunc(void); static int g_numCalls = 0; static int g_numCalls = 0; void someFunc(void) { fprintf(stderr, "Num Calls to %s: %d\n", __func__, g_numCalls); ... } int main(void) { fprintf(stderr, "Num Calls to %s: %d\n", __func__, g_numCalls); someFunc(); someFunc(); ... } compile line: gcc -Wall -ansi util.c test.c -o test 45 The two variables "g_numCalls" have no relation. Think of them as private to each file. C++ Modifiers Storage Classes: suggest/demand where/ how to store a variable Qualifiers: tell the type checker something useful about the value stored 46 Storage Classes static outside of class means: "non-exported global" (deprecated, use anonymous namespace) inside of class means: "class (global) variable" inside of function means: "global only accessible locally" extern: defined somewhere else C++ in different files may define a global variable we're interested in (one that is not static) auto: local stack variable (you probably won't ever see this modifier because it is the default) register: request compiler to store in a register 47 Qualifiers const: cannot be modified (sort of) Constants are handy to define "variables" that won't change after creation Any attempt to change a constant will result in a compile time error You can get around this via the const_cast volatile: another external program might change it These are mostly handy within OS code If an interrupt might suddenly step in and change some value, this lets the compiler know that it should not under any circumstances optimize the value 48 Summary To Do: Read Ch 1-3 Homework #1 Next Time: Data Lab 49 ...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online