. Welcome to PLAB
Course Staff Teacher: Nir Friedman Teaching Assistants: Yoseph Barash Liad Blumrosen Michael Okun
Communications WWW: Personal questions should be sent only to u Newsgroups: local.course.plab.stud local.course.plab.ta (moderated)
Course Objectives u Procedural programming language (C). u Pointers (C/C++) u Generic programming (C++ templates) u Design patterns (STL, streams, and more) u Practice of programming: Style Testing & Debugging Efficiency & Portability Modularity
Books u “The C Programming Language”, 2 nd Edition, Brian W. Kernighan & Dennis M.Ritchie u “C++ Programming Language”, 3 rd Edition, Bjarne Strousrtup u “The C++ Primer”, Stanley Lippman u “C++ for Java Programmers”, Timothy Budd u “C++ How to Program”, Harvey Deitel & Paul Deitel u “The Practice of Programming”, Brian W. Kernighan & Rob Pike u “Programming Pearls” 2 nd Edition, Jon Bentley
Course Grading u 6-7 programming exercises u Mid-term exam u Final exam u Final grade 60% exercises and 40% exam. u Shortage in computers - don’t wait for the last minute.
History CC++ JAVA 70 ’ s – Development of UNIX. (Richie+Kernigham – Bell labs) 80 ’ s – Large efficient code. (Stroustrup – Bell labs) 90 ’ s – Language for the web. (Sun Microsystems) Simple to convert to machine code. Advanced Programming Fast and EfficientSecure and Safe Welcome to Plab Easy to avoid bugs Easy to Debug
C – Design Decisions u “Bare bones” – the language leaves maximal flexibility with the programmer Efficient code (operating systems) Full control on memory & CPU usage u High-level Type checking High-level constructs u Portable Standard language definition Standard library
C – Warning Signs u No run-time checks Array boundary overruns Illegal pointers u No memory management Programmer has to manage memory
C++ - OO extension of C u Classes & methods OO design of classes u Generic programming Template allow for code reuse u Stricter type system u Some run-time checks & memory control
First Program in C // This is a comment // This line defines standard I/O library #include // main – name of the main part of the program int main() { // {…} define a block printf("Hello class!\n"); return 0; }
Compiling & Running… > g++ -o hello hello.c > hello Hello class! >
Second Program #include int main() { int i; // declares i as an integer int j = 0; // declares j as an integer, and initializes it to 0 // for( initial ; test condition ; update step ) for( i = 0; i < 10; i++ ) { j += i; // shorthand for j = j + i printf("%d %d %d\n", i, j, (i*(i+1))/2); } return 0; }
Running… > g++ -o loop loop.c > loop
Character Input/Output #include int main() { char c; while( (c = getchar()) != EOF ) putchar(c); return 0 }
Print header #include #define HEADER 10 int main() { int n = 0; char c; while( ((c = getchar()) != EOF) && (n < HEADER) ) { putchar(c); if( c == '\n' ) n++; } return 0; }
Functions C allows to define functions Syntax: int power( int a, int b ) { … return 7; } Return type Parameter declaration Return statement
Procedures Functions that return void void proc( int a, int b ) { … return; } Return w/o value (optional)
Example – printing powers #include int power( int base, int n ) { int i, p; p = 1; for( i = 0; i < n; i++ ) p = p * base; return p; } int main() { int i; for( i = 0; i < 10; i++ ) printf("%d %d %d\n", i, power(2,i), power(-3,i) ); return 0; }
Functions Declaration “Rule 1”: A function “knows” only functions which were defined above it. void funcA() {... } void funcB() { funcA(); } void funcC() { funcB(); funcA(); funcB(); } void funcA() {... } void funcB() { funcC(); } void funcC() { funcA(); } Error: funcC is not known yet.
Amendment to “Rule 1” : Use forward declarations. void funcC(int param); // or void funcC(int); void funcA(); {... } void funcB() { …. funcC(7); } void funcC(int param) { …. } Functions Declaration
Powers revisted #include // Forward decleration int power( int m, int n); int main() { int i; for( i = 0; i < 10;i++ ) printf("%d %d %d\n", i, power(2,i), power(-3,i) ); return 0; } int power( int base, int n ) { int i, p; p = 1; while( n > 0 ) { if( n % 2 ) p *= base; base *= base; n /= 2; } return p; }
Program Style u Readability u Common Sense u Clarity u Right focus
What’s in a name u Example #define ONE 1 #define TEN 10 #define TWENTY 20 u More reasonable #define INPUT_MODE 1 #define INPUT_BUFSIZE 10 #define OUTPUT_BUFSIZE 20
What’s in a name Use descriptive names for global variables int npending = 0; // current length of input queue Naming conventions vary numPending num_pending NumberOfPendingEvents …
What’s in a name Compare for( theElementIndex = 0; theElementIndex < numberOfElements; theElementIndex++ ) elementArray[theElementIndex] = theElementIndex; and for( i = 0; i < nelems; i++ ) elem[i] = i; Use short names for locals
What’s in a name Consider int noOfItemsInQ; int frontOfTheQueue; int queueCapacity; … The word “queue” appears in 3 different ways Be Consistent Follow naming guidelines used by your peers
What’s in a name Use active name for functions now = getDate() Compare if( checkdigit(c) ) … to if( isdigit(c) ) … Accurate active names makes bugs apparent
Indentation Use indentation to show structure Compare for(n++; n <100; field[n++] = 0); c = 0; return ‘\n’; to for( n++; n <100; n++) field[n] = 0; c = 0; return ‘\n’;
Expressions Use parens to resolve ambiguity Compare leap_year = y % 4 == 0 && y %100 != 0 || y % 400 == 0; to leap_year = ((y % 4 == 0) && (y %100 != 0)) || (y % 400 == 0);
Statements Use braces to resolve ambiguity Compare if( i < 100 ) x = i; i++; to if( i < 100 ) { x = i; } i++;
Idioms Do not try to make code “interesting” i = 0; while( i <= n – 1 ) array[i++] = 1; … for( i = 0; i < n; ) array[i++] = 1; … for( i = n; --i >= 0; ) array[i] = 1; … for( i = 0; i < n; i++ ) array[i] = 1; This is the common “idiom” that any programmer will recognize
Idioms Use “else if” for multiway decisions if ( cond 1 ) statement 1 else if ( cond 2 ) statement 2 … else if ( cond n ) statement n else default-statement
Idioms if( x > 0 ) if( y > 0 ) if( x+y < 100 ) {... } else printf(“Too large!\n" ); else printf("y too small!\n"); else printf("x too small!\n"); if( x <= 0 ) printf("x too small!\n"); else if( y <= 0 ) printf("y too small!\n"); else if( x+y >= 100 ) printf("Sum too large!\n" ); else {... }
Comments Don’t belabor the obvious // return SUCCESS return SUCCESS; // Initialize “total” to “number_received” total = number_received; Test: does comment add something that is not evident from the code
Comments Introduce each function // random: return a random integer in [0..r] int random( int r ) { return (int)floor(rand()*r); }
Comments A more elaborate function comment // // GammaGreaterThanOne( Alpha ) // // Generate a gamma random variable when alpha > 1. // // Assumption: Alpha > 1 // // Reference: Ripley, Stochastic Simulation, p.90 // Chang and Feast, Appl.Stat. (28) p.290 // double GammaGreaterThanOne( double Alpha ) { …
Comments Don’t comment bad code – rewrite it! … // If result = 0 a match was found so return // true; otherwise return false; return !result; Instead … return matchfound;
Style recap Descriptive names Clarity in expressions Straightforward flow Readability of code & comments Consistent conventions & idioms
Why Bother? Good style: Easy to understand code Smaller & polished Makes errors apparent Sloppy code bad code Hard to read Broken flow Harder to find errors & correct them