Overview of C Kernel Language Overview z Tokens




















![Operator hierarchy z. Postfix operators: (), [], ->, . z. Postfix increment, decrement ++, Operator hierarchy z. Postfix operators: (), [], ->, . z. Postfix increment, decrement ++,](https://slidetodoc.com/presentation_image_h2/c8f68db55e866322399e403b6a16a780/image-21.jpg)











































- Slides: 64
Overview of C++ Kernel Language
Overview z. Tokens z. Types ytype conversions and casts z. Expressions z. Statements z. C++ preprocessor z. Input and output
Tokens z The smallest elements of a program z ASCII characters z Five types of tokens z Literals z Identifiers z Keywords z Operators and Punctuators z Comments
Identify the Tokens comment identifier #include <iostream> // C++ standard I/O int main(int argc, char *argv[]) { literal keyword if (argc > 1) cout << “Hello, ” << argv[1]; operator else cout << “Hello, World”; cout << endl; }
Literals z. Constant of any C++ native type z. Examples: y 3 // an integer literal y 3 L // a long integer ytrue // a boolean literal y 5. 0 // a floating-point number y“ 5” // the string constant 5 y. L’abc’ //a wide character (wchar_t) constant
Literal character constants z ‘a’ alert z ‘\’ backslash z ‘b’ backspace z ‘r’ carriage return z ‘”’ double quote z ‘f’ formfeed z ‘t’ tab z ‘n’ newline z ‘ ’ null character z ‘’’ single quote z ‘v’ vertical tab z ‘101’ octal (ascii ‘A’) z ‘x 041’ hexadecimal (ascii ‘A’) z L’oop’ wchar_t constant
Identifiers z. Usually variable names z. Sequences of letters, digits, and underscores z. Start with letter or underscore z. Naming conventions yvery_long_identifier yvery. Long. Identifier // C and Unix style // Pascal style y. C++ naming conventions more complex than C
Keywords z. Reserved words; ycannot be identifiers yint int; // not a valid identifier name z 46 in C++ vs. 32 in C
Common C++ keywords z asm, auto, bool, break, case, catch, char, class, z const, const_cast, continue, default, delete, do, z double, dynamic_cast, else, enum, explicit, extern, z false, float, for, friend, goto, if, inline, int, long, z mutable, namespace, new, operator, private, z protected, public, register, reinterpret_cast, return, z short, signed, sizeof, static_cast, struct, z switch, template, this, throw, true, try, typedef, z typeid, typename, union, unsigned, using, virtual, z void, volatile, wchar_t, while
Operators and Punctuators z. Operators on native types similar to C yarithmetic operators + - * / % ypointer and member operators -> ->* ylogical operators && || ! yassignment operators = += *=, etc. yrelational operators > < == != >= <=
C++ operator overloading z. Operators can be (re)defined for user types! y. Example: xdefine + for vectors xdefine + for matrices xdefine + for complex numbers z. Some new operators y: : scope resolution
Native C++ Types zbool zchar, wchar_t ymodified with signed or unsigned zint ymodified with signed or unsigned ycan be modified with short or long yint can be dropped! long num; ycan be modified with const or volatile zfloat double long double
Native C++ Types: Bottom Line zbool zchar zint zfloat unsigned double long zpitfalls ysize is machine-dependent ysizeof(‘a’) == sizeof(int) in C, ybut sizeof(char) in C++ (char is smaller than int)
Type Size z. Language standard does not define the size of native types zsizeof(type) operator zlimits. h and float. h y. Defines the largest and smallest type values zinclude <limits> numeric_limits<type>: : max()
Implicit conversions (coercion) z. Occur in mixed expressions z. Widening conversions: int < unsigned < long < unsigned long < float < double < long double z. Widening safe, narrowing unsafe. z. But: narrowing conversions allowed with assignments
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
Explicit conversions (casts) z. C and older C++: unrestricted casts y(type)expr type(expr) zstatic_cast: safe, portable, invertible ystatic_cast<char>(‘A’ + i) zreinterpret_cast: implementation- and system-dependent yreinterpret_cast<int>(&x) zwill talk about two more kinds of casts later
Enumeration Types z. Named integer constants z enum Animal {Cat, Dog, Horse = 5}; z. Tag name, enumerators must be unique z. Implicit conversion to integer yint i = Dog; // assigns 1 to i z. Explicit cast from integer y. Animal anim = static_cast<Animal>i; z. C++ trick: yenum {SIZE = 100}; yreplaces #define SIZE 100
Expressions z. Precedence y. Prioritize among multiple operators (a*=5 -3) y. Learn through experience, use () to be safe z. Associativity y. Associate operands with operators y. Left to right: most common y. Right to left: mainly for assignment operators z. User-defined operators cannot change these!
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
Operator hierarchy z. Postfix operators: (), [], ->, . z. Postfix increment, decrement ++, -z. Unary operators: sizeof, +, -, !, &, *, ~ z. Binary operators: (*, /, %), (+, -), (<<, >>), (<, <=, >, >=), (==, !=), (&), (^), (|), (&&), (||) z. Ternary operators: ? : z. Assignment: =, +=, -=, *=, /=, %= z. Comma: ,
Assignment Expression z. Modifies the left-hand side yf = (a + b) * c; z. Also works as an expression yf = (a=b)*c; ya = b = c = d = e = 4; //rightassociative ya = (b = ( c = (d = (e = 4)))); y. Returns value assigned z. Pitfall: assignment (=) vs equality (==) yif (a = 1) yif (a == 1) // always succeeds // might succeed
C++ Statements Overview z Expressions yexpression ; ycompound z Conditional yif/if-else z Iteration ywhile yfor ydo (not as common as iteration) z switch/case z Formatting conventions
C++ Statements z. Expression ; i = j+k*(p-q); f = fun 1() + fun 2(); i = 5; j = ++i; { i = 12; j = i + 7; }
Statements (Cont. ) zif AND if-else if (expression) statement else statement if (2==a) j = function 1(2, 4); if (ptr != 0) a = ptr->value; else { report. Error(); cleaup(); exit(2); }
Statements (Cont. ) zwhile (expression) statement while ((ptr != 0) && (ptr->value!=target)) { ptr = ptr->next; }
Statements (Cont. ) zfor (expr 1; expr 2; expr 3) statement for (int i=0; i<limit; i++) { do. Something(i); do. More(i); } do. Even. More(i); // Is i defined here ?
Statements (Cont. ) zdo do statement while (expression); do { cout << “Input a number: ”; cin >> x; } while (x==0);
Statements (Cont. ) zswitch (expression) statement switch (grade) { case ‘a’: a. Grades++; break; case ‘b’: b. Grades++; break; case ‘c’: c. Grades++; break; default: fails++; }
Statements (Cont. ) zbreak, continue while (i<limit) { j=fun 1(i); if (j==fail) break; do. More(i); } while (i<limit) { j=fun 1(i); if (j==fail) continue; do. More(i); }
C++ Preprocessor z #include lives on #include <iostream> // note no. h z #define less useful z prevent including a file twice #ifndef __INCLUDENAME_H_ #define __INCLUDENAME_H_ // body of include file here #endif
C++ Preprocessor: #define vs. consts #define pi 3. 14 const float pi = 3. 14; z untyped constant z typed constant #define SIZE ROWS*COLS const int SIZE = ROWS*COLS; z value computed by textual substitution by preprocessor #define SIZE 200 z warning at best z size redefinition! z value computed by compiler expression evaluator const int SIZE = 200; z Compiler will complain z const redefinition not allowed
C++ Preprocessor: macros vs. inline functions #define square(x) ((x)*(x)) inline int square(int x) { return x*x; } z semantics determined by syntactic substitution y cout << square(x++); z standard procedure call semantics y cout << square(x++); y x incremented twice! z Untyped y works with ints, floats, … y square(“abc”) xmight not compile, but. . . y x incremented once z Typed y need square for ints, floats y explicit error when compiling square(“abc”)
Input/Output in C++ z C++ iostream. h instead of stdio. h z Why change? y. Input/output routines in iostream can be extended to new types declared by the user y. The routines are in some senses easier to use y. Some aspects of the routines can be set without having to repeat them (e. g. , setting the desired precision for printing floating point values) z Readings: 2. 1 -2. 11, 15. 1 -15. 4, 17. 1 -17. 8, 16. 1 -16. 7, 18. 1 -18. 6
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
Input/Output z. The C I/O library stdio. h is available yprintf, fprintf, etc. y. Do not use them in this course ! z. The C++ library iostream. h is better y. Type-safe y. Extensible y. Easier to use
Using iostream. h z Include iostream. h instead of stdio. h z 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 z To perform input and output we send messages to one of these objects (or one that is connected to a file)
Iostream Basics z<< is "put to" (insertion) operator z>> is "get from" (extraction) operator z. Three standard streams: cout, cin, cerr z. All native types and string support << and >> y. These operators can be defined for user types! y. Matrix m(5, 5); cout << m;
The Insertion Operator (<<) z To send output to the screen we use the insertion operator on the object cout z Format: cout << Expression; z The compiler figures out the type of the object and prints it out appropriately cout << << 5; // Outputs 5 4. 1; // Outputs 4. 1 “String”; // Outputs String ‘n’; // Outputs a newline
The Extraction Operator (>>) z To get input from the keyboard we use the extraction operator and the object cin z Format: cin >> Variable; z No need for & in front of variable z 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
Chaining Calls z Multiple uses of the insertion and extraction operator can be chained together: cout << E 1 << E 2 << E 3 << … ; cin >> V 1 >> V 2 >> V 3 >> …; z Equivalent to performing the set of insertion or extraction operators one at a time z Example cout << “Total sales are $” << sales << ‘n’; cin >> Sales 1 >> Sales 2 >> Sales 3;
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 word 1[512]; string word 2; // reads two words separated by whitespace cin >> word 1 >> word 2; cout << word 1 << ‘+’ << word 2 << endl; }
Setting the Width z 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
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
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 2 e+01 cout. precision(2); cout << y << 'n'; // Outputs 23 cout. precision(3); cout << y << 'n'; // Outputs 23. 1
Additional I/O Methods z istream. get y Reads a single character from input y Including white space int main() { int ch; while ( (ch = cin. get()) != EOF) cout. put(ch); } z istream. getline(char *buf, int limit, char delim); y Reads line of input up to limit or delim
Manipulators z A manipulator is a simple function that can be included in an insertion or extraction chain z C++ manipulators ymust include iomanip. h to use yseveral are provided to do useful things yyou can also create your own (see 17. 3, 17. 5, 17. 6, 17. 8)
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 52n cout << hex << endl; // Outputs 2 an cout << dec << x << endl; // Outputs 42n
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
Input Status Flags z 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) z Flags stay set and all input fails until clear() function called
Testing Status Flags int x; int total = 0; cin >> x; while (!cin. eof()) { total += x; cin >> x; } cout << “Total is “ << total << endl;
Testing Status Flags Extraction is an operator, returns cin object (can check eof() or other flags after operation): int x; int total = 0; while (!(cin >> x). eof()) total += x; cout << “Total is “ << total << endl;
Integer Input z If none of the flags hex, dec, oct set then we can indicate how an int is formatted with value typed: 42 - decimal 42 052 - octal 52 0 x 2 a - hexadecimal 2 a z If any of these flags set, all input will be treated as being of only that type ynote, in explicit decimal format, 052 read as 52, 0 x 2 a read as 0
Character Input z The extraction operator when applied to a character ignores whitespace z To read any character use the get(char) function, can also provide no argument (works like getchar) char ch; cin >> ch; // Reads next non-whitespace char cin. get(ch); // Reads next character (any) while (cin. get() != ‘n’); // Reads to newline
String Input z Can use arguments of string type like any other variable ylike scanf with %s reads as many chars as typed (may be too many) ycan control by using width(int) function or setw(int) manipulator yignores leading whitespace ystops at first whitespace z Example #include <string> string line; cint >> setw(100) >> line;
String Input with Whitespace Use function get(stringloc, size, delimitchar) yreads string into array at stringloc taking in at most size chars and stopping at delimitchar (default is ‘n’ - you can leave delimitchar off) ystops before delimitchar Use function getline to also read newline character Example: string line; cin. get(line, 100, ’n’); cin. get(line, 100); // or
File I/O z Ability to read/write files z Same usage and functions as standard I/O y User must create (open) the streams manually y Must include both iostream and fstream z Input y ifstream z Output y ofstream z Both y fstream
File Input/Output z Done with the same operations (insertion, extraction) as keyboard input and monitor output z Simply open input or output object with connection to a file and use it where you would use cin or cout z To use yinclude <fstream. h> ycreate input object of type ifstream yor output object of type ofstream
Opening Files z Use open function or include file name when declaring variable: ifstream inobj 1; inobj 1. open(“in 1. dat”) ifstream inobj 2(“in 2. dat”); z To check if file successfully opened check object in condition: if (!inobj 1) cout << “Unable to open file in 1. dat” << endl;
Closing a File Use close() on object to close connection to file: ifstream in(“in. dat”); … in. close();
File Example #include <stdlib. h> #include <iostream. h> #include <fstream. h> void main() { char infname[101]; char outfname[101]; char buffer[101]; cout << ”File to copy from: "; cin >> infname; ifstream in(infname); if (!in) { cout << "Unable to open " << infname << endl; exit(0); }
File Example (cont) cout << "File to copy to: "; cin >> outfname; ofstream out; if (!out) { cout << "Unable to open " << outfname << " -already exists!" << endl; exit(0); } in. getline(buffer, 100); while (!in. eof()) { out << buffer << endl; in. getline(buffer, 100); } in. close(); out. close(); }
File input approaches #include <iostream> #include <fstream> int main() { ifstream in(“file. in”); if (!in) exit(1); string str, line; in >> str; // read word // read line getline(cin, line); in. close(); // close file } #include <iostream> #include <fstream> int main() { ifstream in; in. open(“file. in”); if (in. fail()) exit(1); . . . }
File Output #include <iostream> #include <fstream> int main() { ofstream out(“file. out”); if (!out) exit(1); out << “Written”; out. close(); // close file } #include <iostream> #include <fstream> int main() { ofstream out; out. open(“file. out”); if (out. fail()) exit(1); . . }