540 likes | 552 Views
Dive into the fundamentals of data structures in C++ with this comprehensive course. Learn essential concepts with practical examples, programming exercises, and recommended books. Uncover coding style tips, naming conventions, idioms, and debugging techniques to enhance your skills. Explore object-oriented design, generic programming, and template usage in C++. Ensure code clarity, readability, and maintainability by following best practices. Elevate your programming proficiency and tackle complex algorithms with confidence.
E N D
Course Staff • Teacher : • Ofir Pele • TA: • Teachers of other groups: • Roman Yavich
Communications • WWW: moodle • Forums: • Q & A – ask the staff about material. • Exercises forums.
Course • ~4 programming exercises • Frontal exam
Books & Websites • Books: • A list here: http://www.cprogramming.com/books.html • Recommended for the more advanced stuff: • Scott Meyers “Effective” books (STL, C++). • C++ FAQ – Explaining the complicated stuff, corners etc. • C++ FQA – A bit lot more cynical & pragmatic view of the above
Program style • Take the time for it. Very important. If not followed your code will be “write only”. • Common sense • Read “real” coding guidelines document – will give you insight how important it is. e.g. good one from Microsoft or one from Google. • Principles: • Readability • Common Sense • Clarity • Right focus
What’s in a name • Example #define ONE 1 #define TEN 10 #define TWENTY 20 • 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 • intnpending = 0; // current length of input queue • Naming conventions vary (style) • numPending • num_pending • NumberOfPendingEvents • Be consistent, with yourself and peers.
What’s in a name • Consider (wording) intnoOfItemsInQ; intfrontOfTheQueue; intqueueCapacity; … • The word “queue” appears in 3 different ways • Be consistent, with yourself and peers.
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 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 parenthesesto 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 ( cond1 ) { statement1 } elseif ( cond2 ) { statement2 } … else if ( condn ) { statementn } else { default-statement }
Idioms Compare: if( x > 0 ) if( y > 0 ) if( x+y < 100 ) { ... } elseprintf(Too large!\n" ); elseprintf("y too small!\n"); elseprintf("x too small!\n"); if( x <= 0 ) { printf("x too small!\n"); } elseif( y <= 0 ) { printf("y too small!\n"); }elseif( x+y >= 100 ) {printf("Sum too large!\n" ); }else{ ... }
Comments • Don’t write the obvious • // return SUCCESS return SUCCESS; // Initialize total to number_receivedtotal = number_received; • Test: • Does comment add something that is not evident from the code? • Note: “//” Comments are Not Strict ANSI C, but supported by all modern compilers, and clearer in many cases
Comments • Don’t comment bad code – rewrite it! • … • // If result = 0 a match was found so return // true; otherwise return false; return !result; • Instead • … • returnmatchfound;
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 style bad code • Hard to read • Broken flow • Harder to find errors & correct them
Note - style in slides: • In the slides we try to follow the style we dictate. • Butdue to space restriction we sometimes bend the rules. • Don’t follow everything you see in the slides.
Debugging 101 • “Define” the bug --- reproduce it • Use debugger and printouts (and other tools e.g. valgrind) • Don’t panic --- think! • Divide & Conquer
Why C++ is much more fun than C (C++ FAQ)? Classes & methods - OO design Generic programming - Templates allow for code reuse Stricter type system (e.g. function args) Some run-time checks & memory control A common and mature language that gives you high level and low level control Have fun
Why C++ is much more fun than c (C+ FQA)? Tons of corner cases Duplicate features Cryptic syntax Undecidable syntax (uncompilableprogarms!) No two compilers agree on it Probably one of the hardest computer languages to master. Have fun
History tr1: library additions ('05) auto, lambdas, threading,… Practically current c++ Minor changes Major compilers: Latest versions are starting to implement features from c++11 (prev. c++0x) approved draft
Course Objectives • Learn the language • Practice of programming data structures • Design • Testing & Debugging • Efficiency & Portability • Modularity
First Program in C++ • // This line includes the standard // I/O library file (similar to “copy here this file”) #include<iostream>int main() { std::cout << "Hello class!\n"; return0; }
Compiling & Running… • Visual Studio… • In Linux: • > g++ –Wall hello.cpp –o hello • > hello • Hello class! • >
The missing types Fill in missing types from C, in somewhat crude way
strings in C++ • #include<iostream>#include<string>int main() { std::stringstr; int a; double b; std::cin >> str >> a >> b; if(std::cin.fail()) { std::cerr << "input problem\n"; return1; } std::cout << "I got: "<< str << ' ' << a << ' ' << b << std::endl; } More about string functions: http://www.cppreference.com/cppstring
Boolean variables • #include<iostream>int main() { int a = 5; boolisZero = (a == 0); • // same conditions if(!isZero && isZero==false && isZero!=true && !!! isZero && a ) { std::cout << "a is not zero\n"; } }
User Defined Type - enum • Enumerated data - a set of named constants. • Usage: enum [identifier]{enumerator list} enumSeason { WINTER, // = 0 by default SPRING, // = WINTER + 1 SUMMER, // = WINTER + 2 AUTUMN// = WINTER + 3}; enum {SUNDAY=1, MONDAY, TUESDAY, …}; // nameless enumColor {BLACK,RED,GREEN,YELLOW,BLUE,WHITE=7,GRAY}; // 0 1 2 3 4 7 8
enum enumSeason { WINTER, // = 0 by default SPRING, // = WINTER + 1 SUMMER, // = WINTER + 2 AUTUMN// = WINTER + 3}; enumSeason curr_season;curr_season= AUTUMN; curr_season= 19;// legal, but ugly, g++: warning intSUMMER; // error, redefinitionintprev_season = SUMMER; // legal, but ugly, g++ warning
Use enum to eliminate magic numbers – alternative to #define
C++-11 enum class enumclassSeason : char{ WINTER, // = 0 by default SPRING, // = WINTER + 1 SUMMER, // = WINTER + 2 AUTUMN // = WINTER + 3}; Season curr_season;curr_season= Season::AUTUMN; curr_season= SUMMER; // won’t compile! curr_season= 19; // won’t compile! intprev_season= Season::SUMMER; // won’t compile!
enums – why? • More readable code • Code less error prone • Accessible for debugger • Use of the numerical values is not disabled • bad programming usually!
Overloading Understand and remember. More than syntactic sugar. This is how a lot of stuff works under the hood (e.g. inheritance)
Function overloading - C • #include<stdio.h>void foo() { printf ("foo()\n"); } void foo(int n) { printf ("foo(%d)\n", n); } int main() { foo(12); foo(); return0; } Compilation output: Error: Multiple definition of foo
Function overloading – C++ • #include<iostream>void foo() { std::cout << "foo()\n"; } void foo(int n) { std::cout<<"foo("<<n<<")\n"; } int main() { foo(12); foo(); } Output: Compile, and print: foo(12) foo()
Default parameters • #include<iostream>void foo(int n=5) { std::cout << n; } int main() { foo(); } Output: Compile, and print: foo(5)
Overload resolution • Find all functions with same name “candidates”. Let’s call them • Find which have the correct number of arguments - “viable candidates” • Find with best matching arguments. • if • use that function. • else (0 or more than 1): • emit compilation error.
Memory • int main() { char c; int i,j; double x; c i j x
Arrays • Defines a block of consecutive cells • int main() { int i; int a[3]; i a[0] a[1] a[2]