Presentation is loading. Please wait.

Presentation is loading. Please wait.

Welcome to Data Structures in C++. Course Staff 2 Teacher : Ofir Pele TA: Teachers of other groups: Roman Yavich.

Similar presentations


Presentation on theme: "Welcome to Data Structures in C++. Course Staff 2 Teacher : Ofir Pele TA: Teachers of other groups: Roman Yavich."— Presentation transcript:

1 Welcome to Data Structures in C++

2 Course Staff 2 Teacher : Ofir Pele TA: Teachers of other groups: Roman Yavich

3 Communications 3 WWW: moodle Forums: Q & A – ask the staff about material. Exercises forums.

4 Course 4 1. ~4 programming exercises 2. Frontal exam

5 Books & Websites 5 Books: A list here: http://www.cprogramming.com/books.html http://www.cprogramming.com/books.html Recommended for the more advanced stuff: Scott Meyers “Effective” books (STL, C++). C++ FAQC++ FAQ – Explaining the complicated stuff, corners etc. C++ FQAC++ FQA – A bit lot more cynical & pragmatic view of the above

6 Program style

7 7 1. Take the time for it. Very important. If not followed your code will be “write only”. 2. Common sense 3. Read “real” coding guidelines document – will give you insight how important it is. e.g. good one from Microsoft or one from Google. MicrosoftGoogle Principles : 1. Readability 2. Common Sense 3. Clarity 4. Right focus

8 What’s in a name 8 Example #define ONE 1 #define TEN 10 #define TWENTY 20 More reasonable #define INPUT_MODE 1 #define INPUT_BUFSIZE 10 #define OUTPUT_BUFSIZE 20

9 What’s in a name 9 Use descriptive names for global variables int npending = 0; // current length of input queue Naming conventions vary (style) numPending num_pending NumberOfPendingEvents Be consistent, with yourself and peers.

10 What’s in a name 10 Consider (wording) int noOfItemsInQ ; int frontOfTheQueue ; int queueCapacity ; … The word “queue” appears in 3 different ways Be consistent, with yourself and peers.

11 What’s in a name 11 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

12 What’s in a name 12 Use active name for functions now = getDate() Compare if( checkdigit(c) ) … to if( isdigit(c) ) … Accurate active names makes bugs apparent

13 Indentation 13 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’;

14 Expressions 14 Use parentheses 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);

15 Statements 15 Use braces to resolve ambiguity Compare if( i < 100 ) x = i; i++; To if( i < 100 ) { x = i; } i++;

16 Idioms 16 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

17 Idioms 17 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 }

18 Idioms 18 Compare: 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 {... }

19 Comments 19 Don’t write 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? Note: “//” Comments are Not Strict ANSI C, but supported by all modern compilers, and clearer in many cases

20 Comments 20 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;

21 Style recap 21 Descriptive names Clarity in expressions Straightforward flow Readability of code & comments Consistent conventions & idioms

22 Why Bother? 22 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

23 Note - style in slides: 23 In the slides we try to follow the style we dictate. But due to space restriction we sometimes bend the rules. Don’t follow everything you see in the slides.

24 Debugging

25 Debugging 101 25 1. “Define” the bug --- reproduce it 2. Use debugger and printouts (and other tools e.g. valgrind) 3. Don’t panic --- think! 4. Divide & Conquer

26 From C to C++

27 27 Why C++ is much more fun than C (C++ FAQ)? 1.Classes & methods - OO design 2.Generic programming - Templates allow for code reuse 3.Stricter type system (e.g. function args) 4.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++ FAQ)? 1.Classes & methods - OO design 2.Generic programming - Templates allow for code reuse 3.Stricter type system (e.g. function args) 4.Some run-time checks & memory control A common and mature language that gives you high level and low level control Have fun

28 28 Why C++ is much more fun than c (C+ FQA)? 1.Tons of corner cases 2.Duplicate features 3.Cryptic syntax 4.Undecidable syntax (uncompilable progarms!) 5.No two compilers agree on it Probably one of the hardest computer languages to master. Have fun Why C++ is much more fun than c (C+ FQA)? 1.Tons of corner cases 2.Duplicate features 3.Cryptic syntax 4.Undecidable syntax (uncompilable progarms!) 5.No two compilers agree on it Probably one of the hardest computer languages to master. Have fun

29 History 29 The C++ Prog. Manual (85-90) C++98C++03C++11 Major compilers: Latest versions are starting to implement features from c++11 (prev. c++0x) approved draft Practically current c++ Minor changes auto, lambdas, threading, … tr1: library additions ('05)

30 Course Objectives 30 1. Learn the language 2. Practice of programming data structures Design Testing & Debugging Efficiency & Portability Modularity

31 Course structure 31 The basic mechanism underlying many of the extensions. Overloading The C++ version. Object Oriented programing A hidden monster Copying and Conversion Templates - Generics++. Compile time polymorphism Statics, etc. Other topics

32 First Program in C++ 32 // This line includes the standard // I/O library file (similar to “copy here this file”) #include int main() { std::cout << "Hello class!\n"; return 0; }

33 Compiling & Running… 33 Visual Studio… In Linux: > g++ –Wall hello.cpp –o hello > hello Hello class! >

34 Fill in missing types from C, in somewhat crude way 34 The missing types

35 strings in C++ 35 #include #include int main() { std::string str; int a; double b; std::cin >> str >> a >> b; if(std::cin.fail()) { std::cerr << "input problem\n"; return 1; } std::cout << "I got: "<< str << ' ' << a << ' ' << b << std::endl; } More about string functions: http://www.cppreference.com/cppstring

36 Boolean variables 36 #include int main() { int a = 5; bool isZero = (a == 0); // same conditions if(!isZero && isZero==false && isZero!=true && !!! isZero && a ) { std::cout << "a is not zero\n"; } }

37 Enum (C)

38 User Defined Type - enum Enumerated data - a set of named constants. Usage: enum [identifier]{enumerator list} enum Season { WINTER,// = 0 by default SPRING,// = WINTER + 1 SUMMER,// = WINTER + 2 AUTUMN// = WINTER + 3 }; enum {SUNDAY=1, MONDAY, TUESDAY, …}; // nameless enum Color {BLACK,RED,GREEN,YELLOW,BLUE,WHITE=7,GRAY}; // 0 1 2 3 4 7 8 enum Season { WINTER,// = 0 by default SPRING,// = WINTER + 1 SUMMER,// = WINTER + 2 AUTUMN// = WINTER + 3 }; enum {SUNDAY=1, MONDAY, TUESDAY, …}; // nameless enum Color {BLACK,RED,GREEN,YELLOW,BLUE,WHITE=7,GRAY}; // 0 1 2 3 4 7 8 38

39 enum enum Season curr_season; curr_season= AUTUMN; curr_season= 19; // legal, but ugly, g++: warning int SUMMER; // error, redefinition int prev_season = SUMMER; // legal, but ugly, g++ warning enum Season curr_season; curr_season= AUTUMN; curr_season= 19; // legal, but ugly, g++: warning int SUMMER; // error, redefinition int prev_season = SUMMER; // legal, but ugly, g++ warning 39 enum Season { WINTER,// = 0 by default SPRING,// = WINTER + 1 SUMMER,// = WINTER + 2 AUTUMN// = WINTER + 3 }; enum Season { WINTER,// = 0 by default SPRING,// = WINTER + 1 SUMMER,// = WINTER + 2 AUTUMN// = WINTER + 3 };

40 Use enum to eliminate magic numbers – alternative to #define 40

41 C++-11 enum class 41 Season curr_season; curr_season= Season::AUTUMN; curr_season= SUMMER; // won’t compile! curr_season= 19; // won’t compile! int prev_season= Season::SUMMER; // won’t compile! class char enum class Season : char { WINTER,// = 0 by default SPRING,// = WINTER + 1 SUMMER,// = WINTER + 2 AUTUMN// = WINTER + 3 };

42 enums – why? More readable code Code less error prone Accessible for debugger Use of the numerical values is not disabled bad programming usually! 42

43 Understand and remember. More than syntactic sugar. This is how a lot of stuff works under the hood (e.g. inheritance) 43 Overloading

44 #include void foo() { printf ("foo()\n"); } void foo(int n) { printf ("foo(%d)\n", n); } int main() { foo(12); foo(); return 0; } Function overloading - C 44 Compilation output: Error: Multiple definition of foo

45 Function overloading – C++ 45 #include 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()

46 Default parameters 46 #include void foo(int n=5) { std::cout << n; } int main() { foo(); } Output: Compile, and print: foo(5)

47 Overload resolution 47

48 48 Memory & Arrays (C)

49 Memory 49 int main() { char c; int i,j; double x; cijx

50 Arrays Defines a block of consecutive cells int main() { int i; int a[3]; ia[0]a[1]a[2]

51 Arrays - the [ ] operator 51 int arr[5] = { 1, 5, 2, 1,3 }; /*arr begins at address 40*/ Address Computation Examples: 1. arr[0] 40+0*sizeof(int) = 40 2. arr[3] 40+3*sizeof(int) = 52 3. arr[i] 40+i*sizeof(int) = 40 + 4*i 4. arr[-1] 40+(-1)*sizeof (int) = 36 // can be the code // segment or other variables 15213 404448525660

52 Arrays 52 C does not provide any run time checks int a[4]; a[-1] = 0; a[4] = 0; This will compile and run (no errors?!) …but can lead to unpredictable results. It is the programmer’s responsibility to check whether the index is out of bounds…

53 Arrays C does not provide array operations: int a[4]; int b[4]; a = b; // illegal if( a == b ) // legal. ==0, address comparison. 53

54 Array Initialization 54 int arr[3] = {3, 4, 5}; // Good int arr[] = {3, 4, 5}; // Good - The same int arr[3] = {0}; // Init all items to 0, takes O(n) int arr[4] = {3, 4, 5}; // Bad style - The last is 0 int arr[2] = {3, 4, 5}; // Bad int arr[2][3] = {{2,5,7},{4,6,7}};// Good int arr[2][3] = {2,5,7,4,6,7}; //Good – The same int arr[3][2] = {{2,5,7},{4,6,7}}; // Bad int arr[3]; arr = {2,5,7}; // Bad - array assignment only in initialization


Download ppt "Welcome to Data Structures in C++. Course Staff 2 Teacher : Ofir Pele TA: Teachers of other groups: Roman Yavich."

Similar presentations


Ads by Google