1 / 64

Overview of C++ Kernel Language

Overview of C++ Kernel Language. Overview. Tokens Types type conversions and casts Expressions Statements C++ preprocessor Input and output. The smallest elements of a program ASCII characters Five types of tokens. Literals Identifiers Keywords Operators and Punctuators Comments.

stacy-potts
Télécharger la présentation

Overview of C++ Kernel Language

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Overview of C++Kernel Language

  2. Overview • Tokens • Types • type conversions and casts • Expressions • Statements • C++ preprocessor • Input and output

  3. The smallest elements of a program ASCII characters Five types of tokens Literals Identifiers Keywords Operators and Punctuators Comments Tokens

  4. Identify the Tokens comment identifier #include <iostream> // C++ standard I/O int main(int argc, char *argv[]) { if (argc > 1) cout << “Hello, ” << argv[1]; else cout << “Hello, World”; cout << endl; } literal keyword operator

  5. Literals • Constant of any C++ native type • Examples: • 3 // an integer literal • 3L // a long integer • true // a boolean literal • 5.0 // a floating-point number • “5” // the string constant 5 • L’abc’ //a wide character (wchar_t) constant

  6. ‘\a’ alert ‘\\’ backslash ‘\b’ backspace ‘\r’ carriage return ‘\”’ double quote ‘\f’ formfeed ‘\t’ tab ‘\n’ newline ‘\0’ null character ‘\’’ single quote ‘\v’ vertical tab ‘\101’ octal (ascii ‘A’) ‘\x041’ hexadecimal (ascii ‘A’) L’oop’ wchar_t constant Literal character constants

  7. Identifiers • Usually variable names • Sequences of letters, digits, and underscores • Start with letter or underscore • Naming conventions • very_long_identifier // C and Unix style • veryLongIdentifier // Pascal style • C++ naming conventions more complex than C

  8. Keywords • Reserved words; • cannot be identifiers • int int; // not a valid identifier name • 46 in C++ vs. 32 in C

  9. Common C++ keywords • asm, auto, bool, break, case, catch, char, class, • const, const_cast, continue, default,delete, do, • double, dynamic_cast, else, enum, explicit, extern, • false, float, for, friend, goto,if, inline, int, long, • mutable, namespace, new, operator, private, • protected, public, register, reinterpret_cast, return, • short, signed, sizeof, static, static_cast, struct, • switch, template, this, throw, true, try, typedef, • typeid, typename, union, unsigned, using, virtual, • void, volatile, wchar_t, while

  10. Operators and Punctuators • Operators on native types similar to C • arithmetic operators + - * / % • pointer and member operators -> ->* • logical operators && || ! • assignment operators = += *=, etc. • relational operators > < == != >= <=

  11. C++ operator overloading • Operators can be (re)defined for user types! • Example: • define + for vectors • define + for matrices • define + for complex numbers • Some new operators • :: scope resolution

  12. Native C++ Types • bool • char, wchar_t • modified with signed or unsigned • int • modified with signed or unsigned • can be modified with short or long • int can be dropped! long num; • can be modified with const or volatile • floatdoublelongdouble

  13. Native C++ Types: Bottom Line • bool • char • int unsigned long • float double • pitfalls • size is machine-dependent • sizeof(‘a’) == sizeof(int) in C, • but sizeof(char) in C++ (char is smaller than int)

  14. Type Size • Language standard does not define the size of native types • sizeof(type) operator • limits.h and float.h • Defines the largest and smallest type values • include <limits> numeric_limits<type>::max()

  15. Implicit conversions (coercion) • Occur in mixed expressions • Widening conversions: int < unsigned < long < unsigned long < float < double < long double • Widening safe, narrowing unsafe. • But: narrowing conversions allowed with assignments

  16. Coercion Examples int i; long j = 3; float f = 2.3; char c = ‘P’; i = c; // char promoted to int j = c + 7; // result to long f = i + j; // result to float j = f + i; // dangerous: float // truncated to long

  17. Explicit conversions (casts) • C and older C++: unrestricted casts • (type)expr type(expr) • static_cast: safe, portable, invertible • static_cast<char>(‘A’ + i) • reinterpret_cast: implementation- and system-dependent • reinterpret_cast<int>(&x) • will talk about two more kinds of casts later

  18. Enumeration Types • Named integer constants • enum Animal {Cat, Dog, Horse = 5}; • Tag name, enumerators must be unique • Implicit conversion to integer • int i = Dog; // assigns 1 to i • Explicit cast from integer • Animal anim = static_cast<Animal>i; • C++ trick: • enum {SIZE = 100}; • replaces #define SIZE 100

  19. Expressions • Precedence • Prioritize among multiple operators (a*=5-3) • Learn through experience, use () to be safe • Associativity • Associate operands with operators • Left to right: most common • Right to left: mainly for assignment operators • User-defined operators cannot change these!

  20. Expression Examples You must know the operator hierarchy to evaluate an expression like this: 3 < 4 && 4 > 5 || 2 < 4; // bool int i = 2; 1 + i++ + 3; // int

  21. Operator hierarchy • Postfix operators: (), [], ->, . • Postfix increment, decrement ++, -- • Unary operators: sizeof, +, -, !, &, *, ~ • Binary operators: (*, /, %), (+, -), (<<, >>), (<,<=,>,>=),(==, !=),(&),(^), (|),(&&),(||) • Ternary operators: ?: • Assignment: =, +=, -=, *=, /=, %= • Comma: ,

  22. Assignment Expression • Modifies the left-hand side • f = (a + b) * c; • Also works as an expression • f = (a=b)*c; • a = b = c = d = e = 4; //right-associative • a = (b = ( c = (d = (e = 4)))); • Returns value assigned • Pitfall: assignment (=) vs equality (==) • if (a = 1)// always succeeds • if (a == 1)// might succeed

  23. C++ Statements Overview • Expressions • expression ; • compound • Conditional • if/if-else • Iteration • while • for • do (not as common as iteration) • switch/case • Formatting conventions

  24. C++ Statements • Expression ; i = j+k*(p-q); f = fun1() + fun2(); i = 5; j = ++i; { i = 12; j = i + 7; }

  25. Statements (Cont.) • if AND if-else if (2==a) j = function1(2,4); if (ptr != 0) a = ptr->value; else { reportError(); cleaup(); exit(2); } if (expression) statement if (expression) statement else statement

  26. Statements (Cont.) • while while (expression) statement while ((ptr != 0) && (ptr->value!=target)) { ptr = ptr->next; }

  27. Statements (Cont.) • for for (expr1; expr2; expr3) statement for (int i=0; i<limit; i++) { doSomething(i); doMore(i); } doEvenMore(i); // Is i defined here ?

  28. Statements (Cont.) • do do statement while (expression); do { cout << “Input a number:”; cin >> x; } while (x==0);

  29. Statements (Cont.) switch (expression) statement • switch switch (grade) { case ‘a’: aGrades++; break; case ‘b’: bGrades++; break; case ‘c’: cGrades++; break; default: fails++; }

  30. Statements (Cont.) • break, continue while (i<limit) { j=fun1(i); if (j==fail) break; doMore(i); } while (i<limit) { j=fun1(i); if (j==fail) continue; doMore(i); }

  31. C++ Preprocessor • #include lives on #include <iostream> // note no .h • #define less useful • prevent including a file twice #ifndef __INCLUDENAME_H_ #define __INCLUDENAME_H_ // body of include file here #endif

  32. const float pi = 3.14; typed constant const int SIZE = ROWS*COLS; value computed by compiler expression evaluator const int SIZE = 200; Compiler will complain const redefinition not allowed #define pi 3.14 untyped constant #define SIZE ROWS*COLS value computed by textual substitution by preprocessor #define SIZE 200 warning at best size redefinition! C++ Preprocessor:#define vs. consts

  33. inline int square(int x) { return x*x; } standard procedure call semantics cout << square(x++); x incremented once Typed need square for ints, floats explicit error when compiling square(“abc”) #define square(x) \ ((x)*(x)) semantics determined by syntactic substitution cout << square(x++); x incremented twice! Untyped works with ints, floats, … square(“abc”) might not compile, but... C++ Preprocessor: macros vs. inline functions

  34. Input/Output in C++ • C++ iostream.h instead of stdio.h • Why change? • Input/output routines in iostream can be extended to new types declared by the user • The routines are in some senses easier to use • Some aspects of the routines can be set without having to repeat them (e.g., setting the desired precision for printing floating point values) • Readings: 2.1-2.11, 15.1-15.4, 17.1-17.8, 16.1-16.7, 18.1-18.6

  35. Outline Simple input/output (iostream.h) cout, cin, cerr output insertion operator (<<) and chaining int, float, string input extraction operator (>>) and chaining int string Advanced input/output object flags (setf, unsetf) input status bits manipulators (iomanip.h) file input/output (fstream.h) opening/closing files

  36. Input/Output • The C I/O library stdio.h is available • printf, fprintf, etc. • Do not use them in this course ! • The C++ library iostream.h is better • Type-safe • Extensible • Easier to use

  37. Using iostream.h • Include iostream.h instead of stdio.h • Standard iostream objects: cout - object providing a connection to the monitor cin - object providing a connection to the keyboard cerr - object providing a connection to error streem • To perform input and output we send messages to one of these objects (or one that is connected to a file)

  38. Iostream Basics • << is "put to" (insertion) operator • >> is "get from" (extraction) operator • Three standard streams: cout, cin, cerr • All native types and string support << and >> • These operators can be defined for user types! • Matrix m(5,5); cout << m;

  39. The Insertion Operator (<<) • To send output to the screen we use the insertion operator on the object cout • Format: cout << Expression; • The compiler figures out the type of the object and prints it out appropriately cout << 5; // Outputs 5 cout << 4.1; // Outputs 4.1 cout << “String”; // Outputs String cout << ‘\n’; // Outputs a newline

  40. The Extraction Operator (>>) • To get input from the keyboard we use the extraction operator and the object cin • Format: cin >> Variable; • No need for & in front of variable • The compiler figures out the type of the variable and reads in the appropriate type int X; float Y; cin >> X; // Reads in an integer cin >> Y; // Reads in a float

  41. Chaining Calls • Multiple uses of the insertion and extraction operator can be chained together: cout << E1 << E2 << E3 << … ; cin >> V1 >> V2 >> V3 >> …; • Equivalent to performing the set of insertion or extraction operators one at a time • Example cout << “Total sales are $” << sales << ‘\n’; cin >> Sales1 >> Sales2 >> Sales3;

  42. Basic I/O Example #include <iostream.h> #include <string> int main() { int x, y, z; cin >> x >> y >> z; cout << x << endl << y << endl << z; char word1[512]; string word2; // reads two words separated by whitespace cin >> word1 >> word2; cout << word1 << ‘+’ << word2 << endl; }

  43. Setting the Width • You can use the width(int) function to set the width for printing a value, but it only works for the next insertion command int x = 42; cout.width(5); cout << x << ‘\n’; // Outputs 42 cout << x << ‘\n’; // Outputs 42

  44. Setting the Fill Character Use the fill(char) function to set the fill character. The character remains as the fill character until set again. int x = 42; cout.width(5); cout.fill(‘*’); cout << x << ‘\n’; // Outputs ***42

  45. Significant Digits in Float Use function precision(int) to set the number of significant digits printed (may convert from fixed to scientific to print): float y = 23.1415; cout.precision(1); cout << y << '\n'; // Outputs 2e+01 cout.precision(2); cout << y << '\n'; // Outputs 23 cout.precision(3); cout << y << '\n'; // Outputs 23.1

  46. Additional I/O Methods • istream.get • Reads a single character from input • Including white space int main() { int ch; while ( (ch = cin.get()) != EOF) cout.put(ch); } • istream.getline(char *buf, int limit, char delim); • Reads line of input up to limit or delim

  47. Manipulators • A manipulator is a simple function that can be included in an insertion or extraction chain • C++ manipulators • must include iomanip.h to use • several are provided to do useful things • you can also create your own (see 17.3, 17.5, 17.6, 17.8)

  48. Output Manipulators (no args) Manipulators included like arguments in extraction endl - outputs a new line character, flushes output dec - sets int output to decimal hex - sets int output to hexadecimal oct - sets int output to octal Example: #include <iostream.h> #include <iomanip.h> int x = 42; cout << oct << x << endl; // Outputs 52\n cout << hex << x << endl; // Outputs 2a\n cout << dec << x << endl; // Outputs 42\n

  49. Output Manipulators (1 arg) Manipulators taking 1 argument setw(int) - sets the width to int value setfill(char) - sets fill char to char value setprecision(int) - sets precision to int value setbase(int) - sets int output to hex if int is 16, oct if int is 8, dec if int is 0 or 10 setiosflags(flags) - set flags on resetiosflags(flags) - sets flags off cout << setw(7) << setprecision(2) << setfill(‘_’) << 34.267 << endl; // outputs __34.27

  50. Input Status Flags • When performing input, certain problems may occur, we can determine if an error has occurred by checking these flags: eof() - end-of-file occurred during input fail() - input operation failed good() - no flags set (not eof or any of fail flags) • Flags stay set and all input fails until clear() function called

More Related