820 likes | 956 Views
Christian Schulte cschulte@kth.se Software and Computer Systems School of Information and Communication Technology KTH – Royal Institute of Technology Stockholm, Sweden. Getting Started With C++. ID1218 Lecture 07 2009-11-18. Overview. C++ Basics Basic types and control structures
E N D
Christian Schulte cschulte@kth.se Software and Computer Systems School of Information and Communication Technology KTH – Royal Institute of Technology Stockholm, Sweden Getting Started With C++ ID1218 Lecture 07 2009-11-18
Overview • C++ Basics • Basic types and control structures • Functions and Arrays • Pointers • Some pragmatics… ID1218, Christian Schulte
Goals • Familiarize with programming in C/C++ • Understand underlying programming model • Understand • language constructs • program structure • data structures and common algorithms • memory management • development pragmatics • difference between C and C++ • For later courses using C/C++ ID1218, Christian Schulte
Approach • Not from scratch, build • Java as programming language • Efficient approach • focus on essential • not comprehensive • apply practically ID1218, Christian Schulte
Textbook • C++ for Java Programmers, Mark Allen Weiss, Prentice Hall, 2004 • good selection of issues and topic • non-naïve: no repetition what you know • concise (very important) • valuable resource after course!!! ID1218, Christian Schulte
Other Valuable Books: C++ • Thick, verbose, but useful J. Lajoie and S. Lippmann, C++ Primer 3rd edition, Addison-Wesley, 1998. • Reference from the designer B. Stroustrup, The C++ Programming Language 3rd edition, Addison-Wesley, 1997. • Tips for advanced issues R. B. Murray, C++ Strategies and Tactics Addison-Wesley, 1993. • C++ Standard library N. M. Josuttis, The C++ Standard Library Addison-Wesley, 1999. ID1218, Christian Schulte
Other Valuable Books: C • The classic B. W. Kernighan and D. M. Ritchie, The C Programming Language 2nd edition, Prentice Hall, 1997 • Great reference, portability, also useful for C++ S. P. Harbinson, G. L. Steele, C – A Reference Manual 5th edition, Prentice Hall, 2002 ID1218, Christian Schulte
What? • C++ as main vehicle • basic issues • pointers and references • classes, objects, inheritance • overview: operator overloading, templates, exceptions, input/output, standard library • Contrast with main differences in C • basic issues (arrays) • memory management, input/output • mixing C and C++ ID1218, Christian Schulte
Why? • Study radically different model of computation • not type safe: how to get along • explicit memory management: no garbage collection, how to manage memory successfully • close to abstraction level of machines • Ideally, do it in Erlang… …but can't be done • take the trouble and use C++/C • can be used afterwards anyway ID1218, Christian Schulte
How? • Differential approach • in contrast to Java: Java is close in many aspects • Practical approach • try most important aspects in labs/tutorials ID1218, Christian Schulte
What Do I Expect? • You will not become C++ wizards • You will understand the basic issues • characteristics of computation model • characteristics of development pragmatics • You will know where to look for further information • language • pragmatics ID1218, Christian Schulte
Pragmatics • How to organize programming projects • automatize recompilation make • How to install software • use configure • How to develop • how to find errors: debugging • how to improve performance: profiling ID1218, Christian Schulte
Labs • Labs • warm-up: introduction to pragmatics • sound processing: to be handed in • Sudoku solver: to be handed in • Hand in: show to TA ID1218, Christian Schulte
Reading Suggestions • All of you • thorough reading of chapters 0 to 3 • take a peek at chapter 11 • do it, the book is a great read! • go through the exercises! ID1218, Christian Schulte
Getting Started in C++ ID1218, Christian Schulte
Our First C++ Program #include <iostream> using namespace std; int main() { cout << "Hello world." << endl; return 0; } ID1218, Christian Schulte
Hello World Explained • Execution starts with main • integer return value is error code (0 is okay) • is normal function (a global function) • functions in classes (methods): member functions • can take additional arguments (command-line): later • All C++ programs are preprocessed • #include <…> resolved by preprocessor • <iostream> refers to C++ system IO • #include "my.h" includes local file my.h • Other uses: multiply used files (declarations, headers) ID1218, Christian Schulte
Hello World Explained… • Standard functionality in namespace std • becomes available by using namespace std; • here: cout (standard output), endl (end of line) • Input similarly: int x; cout << "Your age: "; cin >> x; • cin refers to standard input • also common: using C-style input/output ID1218, Christian Schulte
In Java… public class Hello { public static void main(String[]) { System.out.println("Hello world"); } } ID1218, Christian Schulte
Compiling and Running • Edit file emacs hello.cpp • other extensions: .cc, .cxx, .C • Invoke compiler to create executable g++ hello.cpp –o hello.exe • we use the GNU C++ compiler (g++) • Run executable ./hello.exe ID1218, Christian Schulte
Basic Types and Control Structures ID1218, Christian Schulte
Primitive Types • Integer types • Floating point types • Character types • Boolean type • Non-primitive types • arrays, objects, pointers, references, … ID1218, Christian Schulte
Integer Types • Basic integer type int • few guarantees on range in C++ • today, often 32 bits, anytime soon 64 bits, … • depends on machine (think of embedded…) • Can be augmented with short or long • int never shorter than short int (at least 16) • int never longer than long int (at least 32) • Can be modified with signed (default) or unsigned • short signed int -32768 … 32767 • short unsigned int 0 … 65535 • just for example! ID1218, Christian Schulte
Floating Point Types • Single precision float • often: 32 bits • Double precision double • often: 64 bits • Again, few guarantees ID1218, Christian Schulte
Character Type • Character type char • no guarantee on size, often 8 bits (ASCII, not Unicode!) • unspecified whether signed or unsigned • Character constants in single quotes • 'a','1' • escape sequences: '\n' for newline, etc • Also available: wchar_t for wide characters ID1218, Christian Schulte
Boolean Type • Boolean type bool • constants true and false • Rather late addition! • watch out for int with zero as false and any other value true! ID1218, Christian Schulte
Constants • Variables taking an immutable value • cannot be changed • abbreviation for commonly used values • Use const modifier const double pi = 3.1415; • assignment to pi not possible ID1218, Christian Schulte
Operators, Expressions, Statements • Almost the same in C++ as in Java • in general: C++ carries some historic weight, Java has cleaned up, so watch out for some gotchas • Almost the same • operators and expressions, conditionals, loops, … • assignment: no guarantee of initialization • Additionally • casts: change/convert/ignore type • type definitions ID1218, Christian Schulte
Operators and Expressions • No left to right order readInt() – readInt() with input 2 and 3 can be either 1 or -1 • Integer division not guaranteed to round towards zero (book uses down) 8/-5 can be either -1 or -2 • Comma operator: a,b evaluates to b • weird things possible! ID1218, Christian Schulte
Operators and Expressions • No guarantee on shift a << b • can be either arithmetic or logic • arithmetic -1 << 1 remains negative • logic -1 << 1 is positive ID1218, Christian Schulte
Conditionals • Condition can be either of type int or bool if (i) { … } else { … } • If i is different from zero, take then part • If i is zero, take else part • not recommended, write if (i != 0) … • Common mistake if (x = 0) … • actually meant: if (x == 0) … • assigns 0 to x, takes the else part • write variable to the right, if possible: if (0 == x) ID1218, Christian Schulte
Loops • As in Java, along with break and continue ID1218, Christian Schulte
Unitialized Variables • Variables not by guarantee initialized • unless global or static (later) • Always give initial value • important for objects (later) ID1218, Christian Schulte
Typecasts for Primitive Types • Automatic conversion double x = 6.0; int y; y=x; • Typecasting can be essential int x=6; int y=10; double z = x/y; • results in 0.0 rather than 0.6 ID1218, Christian Schulte
Static Casts • Cast at least one into double static_cast<double>(x)/y; • Other casts • dynamic_cast casting objects, later • const_cast later • reinterpret_cast just do it as size fits… • C-style cast ((double) x) • dangerous, combines everything, don't use! ID1218, Christian Schulte
Type Definitions • Give names to types • Example: define implementation dependent integer type uint32 • machine A: typedef unsigned long int uint32; • machine B: typedef unsigned int uint32; • rest of program can use uint32, does not require modification when being ported to machine C ID1218, Christian Schulte
Functions ID1218, Christian Schulte
Function Definition • Function definition contains • return type • function name • parameter list • body • Function can be called given function name and appropriate parameters • Function can only be defined once ID1218, Christian Schulte
Function Example int maxx(int x, int y) { return (x > y) ? x : y; } ID1218, Christian Schulte
Function Invocation • Print maximum of two numbers cout << maxx(43,27) << endl; • Uses call-by-value • Parameters need not be of type int • automatic cast long int • possibly with warning ID1218, Christian Schulte
Function Overloading • The same function name can be used multiply with different types in parameter list double maxx(double x, double y) { return (x>y) ? x : y; } • Complicated set of rules describe which definition is chosen • Overloading with different return type only not allowed ID1218, Christian Schulte
Function Declarations • Every function needs to be declared prior to invocation • declared, but not defined! • can be declared multiply • A function declaration is done by giving a function prototype int maxx(int, int); or int maxx(int a, int b); ID1218, Christian Schulte
Default Parameters • Default values can be given for formal parameters • if function has declaration, in declaration • if function has only definition, in definition • only allowed as last formal parameters • Assume that maxx is often used with 0 as second argument int maxx(int, int = 0); Then the following invocation is legal int z = maxx(-45); • In this case, definition remains unchanged ID1218, Christian Schulte
Inline Functions • Overhead of function call be significant: maxx is good example • Give function definition an inline directive inline int maxx(int x, int y) { … } • Invocation of function is replaced by body • Definition must be textually before first invocation • Compilers will also inline other, small functions ID1218, Christian Schulte
Separate Compilation • Structure larger programs into separate files • each file contains some functions: better structure • each file can be compiled independently: save compilation time during development • Header file • contains declarations and definitions of inline functions • file name extensions: .h, .hh • Implementation file • contains definition of functions (implementation) ID1218, Christian Schulte
Header File maxx.h /* * Declaration of maximum function */ int maxx(int, int); ID1218, Christian Schulte
Implementation File maxx.cpp #include "maxx.h" int maxx(int x, int y) { return (x > y) ? x : y; } ID1218, Christian Schulte
Main File main.cpp #include <iostream> #include "maxx.h" int main() { std::cout << maxx(47,23) << std::endl; return 0; } ID1218, Christian Schulte
Putting Everything Together • Compile each implementation file independently g++ -c main.cpp g++ -c maxx.cpp • creates the files main.o and maxx.o • contain object code but require linking • Put everything together (linking) g++ main.o maxx.o –o main.exe ID1218, Christian Schulte
Include Each Header at Most Once • Remember: inline functions must be defined not only declared before usage • Remember: at most one definition! • what if header is included from other header files • possibly having multiple definitions of same function • also: why read same header more than once? • Use preprocessor (also macro processor) to guarantee at-most-once inclusion • define a preprocessor variable when included • test whether preprocessor variable not already defined • choose reasonably unique name ID1218, Christian Schulte