Guest User

C++ Primer Notes

a guest
Nov 8th, 2014
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 160.15 KB | None | 0 0
  1. /*Chapter 1*/
  2. While Statement: Repeatedly executes a section of code so long as a given condition is true.
  3. Condition: Is an expression that yields a result that is either true or false. It goes inside the ()
  4. For statement:
  5. for (int val = 1; val <= 10; ++val)
  6. Each for statement has two parts: a header and a body.
  7.     The header controls how often the body is executed.
  8.     an int statement (val = 1)
  9.     a condition (val <= 10)
  10.     and an expression (++val)
  11. The variable val exists only inside the for; it is not possible to use val after this loop terminates
  12. The init-statement is executed only once, on entry to the for
  13. The condition (val <= 10) is tested each time through the loop. As long as val is less than or equal to 10, we excute the for body.
  14. The expression is executed after the for body (it skips the first ++val and goes to the body first then back to the ++val and loops)
  15. After executing the expression, the for retests the condition.
  16.  
  17.  
  18. /*Chapter 2*/
  19. #Table Types:
  20. Type:           Meaning:                            Minimum Size
  21. bool            boolean                             NA
  22. char            character                           8 bits
  23. wchar_t         wide character                      16 bits
  24. char16_t        Unicode character                   16 bits
  25. char32_t        Unicode character                   32 bits
  26. short           short integer                       16 bits
  27. int             integer                             16 bits
  28. long            long integer                        32 bits
  29. long long       long integer                        64 bits
  30. float           single-precision floating-point     6 significant digits
  31. double          double-precision floating-point     10 significant digits
  32. long double     extended-precision floating-point   10 significant digits
  33.  
  34. Group           Type names*             Notes on size / precision
  35. Character types
  36.                 char                    Exactly one byte in size. At least 8 bits.
  37.                 char16_t                Not smaller than char. At least 16 bits.
  38.                 char32_t                Not smaller than char16_t. At least 32 bits.
  39.                 wchar_t                 Can represent the largest supported character set.
  40. Integer types (signed) 
  41.                 signed char             Same size as char. At least 8 bits.
  42.                 signed short int        Not smaller than char. At least 16 bits.
  43.                 signed int              Not smaller than short. At least 16 bits.
  44.                 signed long int         Not smaller than int. At least 32 bits.
  45.                 signed long long int    Not smaller than long. At least 64 bits.
  46. Integer types (unsigned)
  47.                 unsigned char           (same size as their signed counterparts)
  48.                 unsigned short int
  49.                 unsigned int
  50.                 unsigned long int
  51.                 unsigned long long int
  52. Floating-point types
  53.                 float  
  54.                 double                  Precision not less than float
  55.                 long double             Precision not less than double
  56. Boolean type
  57.                 bool   
  58. Void type      
  59.                 void                    no storage
  60. Null pointer
  61.                 decltype(nullptr)  
  62.  
  63. 0 = False
  64. 1 = True
  65.  
  66. Except for bool and extended character types, the integral types may be <signed> or <unsigned>. A signed type represents negative or positive numbers (including zero); an unsigned type represents only values greater than or equal to zero.
  67. The types int, short, long and long long are all signed. We obtain corresponding unsigned type by adding unsigned to the type, such as "unsigned long". The type unsigned int may be appreviated as unsigned
  68. In an unsigned type, all the bits represent the value. For ex., an 8-bit unsigned char can hold the values from 0 through 255 inclusive.
  69.  
  70. We can write an integer literal using decimal, octal, or hexadecimal notation. Integer literals that begin with 0 are interpreted as octal. 0x or 0X are interpreted as hex.
  71.     Ex. 20 // decimal
  72.         024 // octal
  73.         0x14 // hexadecimal
  74.  
  75. #Table 2.2
  76. //Character and Character String Literals
  77. Prefix      Meaning                 Type
  78. u           Unicode 16 character    char16_t
  79. U           Unicode 32 character    char32_t
  80. L           Wide character          wchar_t
  81. u8          utf-8 (string literals) char
  82.  
  83. //Integer Literals
  84. Suffix      Minimum Type
  85. u or U      Unsigned
  86. l or L      Long
  87. ll or LL    Long long
  88. //Floating-Point literals
  89. Suffix      Type
  90. f or F      Float
  91. l or L      Long Double
  92.  
  93. Floating-point literals include either a decimal point or an exponent specified using scientific notation. Using scientific notation, the exponenet is indicated by either E or e:
  94. 3.14159     3.14159E0       0.      0e0     .001
  95.  
  96. #Nonprintable Characters
  97. newline             \n      horizontal tab      \t      alert (bell)        \a
  98. verticle tab        \v      backspace           \b      double quote        \"
  99. backslash           \\      question mark       \?      single quote        \"
  100. carriage return     \r      formfeed            \f 
  101.  
  102.     int units_sold = 0;
  103.     int units_sold = {0};
  104.     int units_sold{0};
  105.     int units_sold(0);
  106.    
  107. The generalized use of curly braces for initialization was introduced as part of the new standard. This form of initialization previously had been allowed only in more restricted ways. This form of initialization is referred to as <list initialization>.
  108. Braced lists of initializers can now be used whenever we initialize an object and in some cases when we assign a new value to an object.
  109. When we used the variables of built-in type, this form of initialization has one important property: The compiler will not let us list initialize variables of built-in type if the initializer might lead to the loss of information
  110.  
  111. Declaration: makesa  name known to the program.
  112. Definition: creates the associated entity.
  113.  
  114. To obtain a declaration that is not also a definition, we add the extern keyword and may not provide an explicit initializer:
  115. extern int i;   //  declares but does not define i
  116. int j   //  declares and defines j
  117.  
  118. #Table 2.3 C++ Keywords
  119. alignas     continue        friend      register            true
  120. alignof     decltype        goto        reinterpret_cast    try
  121. asm         default         if          return              typedef
  122. auto        delete          inline      short               typeid
  123. bool        do              int         signed              typename
  124. break       double          long        sizeof              union
  125. case        dynamic_cast    mutable     static              unsigned
  126. catch       else            namespace   static_assert       using
  127. char        enum            new         static_cast         virtual
  128. char16_t    explicit        noexcept    struct              void
  129. char32_t    export          nullptr     switch              volatile
  130. class       extern          operator    template            wchar_t
  131. const       false           private     this                while
  132. constexpr   float           protected   thread_local
  133. const_cast  for             public      throw
  134.  
  135. #Table 2.4 C++ Alternative Operator Names
  136. and     bitand      compl       not_eq      or_eq       xor_eq
  137. and_eq  bitor       not         or          xor
  138.  
  139. Reference: Defines an alternate name for an object. A reference "refers to" another type. (&variable)
  140. Pointer: Compound type that "poitns to" another type (*variable)
  141.     (A pointer holds the address of another object. We get the address of an object by using the address-of operator (the <& operator>))
  142.     int *p = &number (pointer point is of type int that holds the address of number)
  143.     (When a pointer points to an object, we can use the dereference operator ( the <* operator>) to access that object)
  144.     cout << *p << endl;
  145.  
  146. Type Alias: Name that is a synonym for another type. (typedef and using)
  147.  
  148. struct (variable) { type variable; type variable2; type variable3; ..};
  149.  
  150. #ifndef SALES_DATA_H
  151. #define SALES_DATA_H
  152. #include <string>
  153. struct Sales_data
  154. {
  155.     string bookNo;
  156.     unsigned units_sold = 0;
  157.     double revenue = 0.0;
  158. };
  159. #endif
  160.  
  161. /*Chapter 3*/
  162. using std::cin; using std::cout; using std::endl; using std::string;
  163.  
  164. Code inside headers ordinarily should not use using declarations. The reason is that the contents of a header are copied inot the including program's text. If a header has a using declaration, then every program that includes that header gets the same
  165. using declaration. As a result, the program that didn't intend to use the specified library name might encounter unexpected name conflits.
  166.  
  167. #Table 3.1 Ways to Initialize a string
  168. string s1           //  Default initialization; s1 is the empty string.
  169. string s2(s1)       //  s2 is a copy of s1.
  170. string s2 = s1      //  Equivalent to s2(s1), s2 is a copy of s1.
  171. string s3("value")  //  s3 is a copy of the string literal, not including the null.
  172. string s3 = "Value" //  Equivalent to s3("Value"), s3 is a copy of the string literal.
  173. string s4(n, 'c')   //  Initialize s4 with n copies of the character 'c'.
  174.  
  175. #Table 3.2 string Operations
  176. os << s         //  Writes s onto output strom os. Returns os.
  177. is >> s         //  Reads whitespace-separated string from is inot s. Returns is.
  178. getline(is, s)  //  Reads a line of input from is inot s. Returns is.
  179. s.empty()       //  Returns true if s is empty; otherwise returns false
  180. s.size()        //  Returns the number of characters in s.
  181. s[n]            //  Returns a reference to the character at position n in s; positions start at 0.
  182. s1 + s2         //  Returns a string that is the concatentation of s1 and s2.
  183. s1 = s2         //  Replaces characters in s1 with a copy of s2.
  184. s1 == s2        //  The strings s1 and s2 are equal if they contain the same characters.
  185. s1 != s2        //  Equality is case-senitive.
  186. <,<=, >, >=     //  Comparisions are case-sensitive and use dicitionary ordering.
  187.  
  188. #Reading and Writing strings
  189. As we saw in chapter 1, we use the iostream library to read and write values of built-in types such as int, double, and so on. We use the same IO operators to read and write strings:
  190. int main()
  191. {
  192.     string s;           //  empty string
  193.     cin >> s;           //  read a whitespace-separated string inot s
  194.     cout << s < endl;   //  writes s to the output
  195.     return 0;
  196. }
  197.  
  198. //  using getline to return a whole input, not one word at a time
  199. int main()
  200. {
  201.     string line;
  202.     //  read input a line at a time until end-of-file
  203.     while (getline(cin, line))
  204.         cout << line << endl;
  205.     return 0;
  206. }
  207.  
  208. Although we don't know the precise type of string::size_type, we do know that is an unsigned type big enough to hold the size of any string. Any variable used to store the result from the string size operation should be of type string::size_type.
  209. Admittedly, it can be tedious to type string::size_type. Under the new standard, we can ask the compiler to privde the appropriate type by using auto or decltype:
  210. size_type sizet = line.size()
  211. auto len = line.size(); //  len has type string::size_type
  212.  
  213. The equality operators (== and !=) test whether the type strings are equal or unequal, respectively. Two strings are equal if they are the same length and contain the same charcaters. The relational operators <, <=, >, >= test whether one string
  214. is less than, less than or equal to, greater than, or greater than or equal to another. These operators use the same strategy as a (case-sensitive) dictionary:
  215. 1. If two strings have different lengths and if every character in the shorter string is equal to the corresponding character of the longer string, then the shorter string is less than the longer one.
  216. 2. If any characters at corresponding positions in the two string differ, then the result of the string comparision is the result of comparing the first character at which the strings differ.
  217.  
  218. string str= "Hello";            //  less than phrase, rule 1
  219. string phrase = "Hello World";
  220. string slang = "Hiya";          //  greater than both, rule 2
  221.  
  222. When we mix strings and string or character literals, at least one operand to each + operator must be of string type:
  223. string s4 = s1 + ", ";              //  ok: adding a string and a literal
  224. string s5 = "hello" + ", ";         //  error: no string operand
  225. string s6 = s1 + ", " + "world";    //  ok: each + has a string operand
  226. string s7 = "hello" + ", " + s2;    //  error: can't add string literals
  227.  
  228. The initializations of s4 and s5 involve only a single operation each, so it is easy to see whether the initiailization is legal. The initialization of s6 may appear surprising, but it works in much the same way when we chain together input or output
  229. expressions. This initialization groups as
  230. string s6 = (s1 + ", ") + "world";
  231.  
  232. ****Warning****
  233.     For historical reasons, and for compatibility with C, string literals are not standard library strings. It is important to remember that these types differ when you use string literals and library strings.
  234.    
  235. #Table 3.3 cctype Functions
  236. isalnum(c)  //  true if c is a letter of digit.
  237. isalpha(c)  //  true if c is a letter.
  238. iscntrl(c)  //  true if c is a control character.
  239. isdigit(c)  //  true if c is a digit.
  240. isgraph(c)  //  true if c is not a space but is printable.
  241. islower(c)  //  true if c is a lowercase letter.
  242. isprint(c)  //  true if c is a printable character (i.e., a space or a character that has a visible representation).
  243. ispunct(c)  //  true if c is a punctuation character (i.e., a character that is not a control character, a digit, a letter, or a priintable whitespace).
  244. isspace(c)  //  true if c is a whitespace (i.e., a space, tab, vertical tab, return, newline, or formfeed).
  245. isupper(c)  //  true if c is an uppercase letter.
  246. isxdigit(c) //  true if c is a hexadecimal digit
  247. tolower(c)  //  If c is an uppercase letter, returns its lowercase equivalent; otherwise returns c unchanged.
  248. toupper(c)  //  If c is a lowercase letter, turns its uppercase equivalent; otherwise returns c unchanged.
  249.  
  250. //Range for: do something to every character in a string. Statement iterates through the elements in a given sequence.
  251. for (declaration : expression)
  252. {
  253.     statement
  254. }
  255.  
  256. string str("some string");
  257. //  print the character in str one character to a line
  258. for (auto c : str)      //  for every character in str
  259. {
  260.     cout << c << endl;      //  print the current character followed by a new line
  261. }
  262.  
  263. string s("Hello World!!!");
  264. //  punct_cnt has the same type that s.size returns
  265. decltype(s.size()) punct_cnt = 0;
  266. //  count the number of punctuation characters in s
  267. for (auto c : s)            //  for every char in s
  268. {
  269.     if (ispunct(c))         //  if the character is a punctuation
  270.     {
  271.         ++punct_cnt;        //  increment the punctuation counter
  272.     }
  273. }
  274. cout << punct_cnt << " punctuation characters in " << s << endl;
  275.  
  276. string s("Hello World!!!");
  277. //  convert s to uppercase
  278. for ( auto &c : s)  //  for every char in s (note: c is a reference)
  279. {
  280.     c = toupper(c); //  c is a reference, so the assignment changes the char in s
  281. }
  282. cout << s << endl;
  283.  
  284. if (!s.empty())             //  make sure there's a character to print
  285. {
  286.     cout << s[0] << endl;   //  print the first character in s
  287. }
  288.  
  289. string s("some string");
  290. if (!s.emtpy())             //  make sure there's a character in s[0]
  291. {
  292.     s[0] = toupper(s[0]);   //  assign a new value to the first character in s
  293.     //  Prints "Some string"
  294. }
  295.  
  296. string s("some string");
  297. //  process characters in s until we run out of characters or we hit a whitespace
  298. for (decltype(s.size()) index = 0; index != s.size() && !isspace(s[index]); ++index)
  299. {
  300.     s[index] = toupper(s[index]);   //  capitalize the current character
  301. }
  302. cout << s << endl;
  303. //  Prints "SOME string"
  304.  
  305. ****Caution: Subscripts are Unchecked****
  306.     When we use a subscript, we must ensure that the subscript is in range. That is, the subscript must be >= 0 and < the size() of the string. One way to simplify code that uses subscript is to always use a varaible of type string::size_type
  307.     as the subscript. Because that type is unsigned, we ensure that the subscript cannot be less than zero. When we use a size_type value as the subscript, we need to check only that our subscript is less than the value returned by size().
  308.  
  309. const string hexdigits = "0123456789ABCDEF";    //  possible hex digits
  310. cout << "Enter a series of numbers between 0 and 15 seperated by spaces, Hit ENTER when finished:" << endl;
  311. string result;          //  will hold the resulting hexify'd string
  312. string::size_type n;    //  hold numbers from the input, string::size_type is a very large numerical type
  313. while (cin >> n)
  314. {
  315.     if (n < hexdigits.size())   //  ignore invalid input
  316.     {
  317.         result += hexdigits[n]; //  fetch the indicated hex digit
  318.     }
  319.     cout << "Your hex number is " << result << endl;
  320. }
  321.  
  322. #Vector
  323. Vector: A collection of objects, all of which have the same type. Often referred to as a "container" because it "contains" other objects.
  324.  
  325. #Table 3.4 Ways to Initialize a vector
  326. vector<T> v1                    //  vector that holds objects of type t. Default initialization. v1 is empty
  327. vector<T> v2(v1)                //  v2 has a copy of each element in v1.
  328. vector<T> v2 = v1               //  Equivalent to v2(v1), v2 is a copy of the elements in v1.
  329. vector<T> v3(n, val)            //  v3 has n elements with value val.
  330. vector<T> v4(n)                 //  v4 has n copies of a value-initialized object.
  331. vector<T> v5{a,b,c...}          //  v5 has as many elements as there are initializers; elements are initialized by corresponding initializers.
  332. vector<T> v5 = {a,b,c...}       //  Equivalent to v5{a,v,c...}.
  333.  
  334. vector<int> ivec;           //  initially empty
  335. //  give ivec some values
  336. vector<int> ivec2(ivec);    //  copy elements of ivec inot ivec2
  337. vector<int> ivec3 = ivec;   //  copy elements of ivec inot ivec3
  338. vector<string> svec(ivec2); //  error: svec holds strings, not ints
  339.  
  340. #List Initializing a vector
  341. vector<string> articles = {"a", "an", "the"};   //  List initialization uses curl braces ({})
  342.  
  343. #List Initializer or Element Count?
  344. In a few cases, what initialization means depends upon whether we use curly braces or parentheses to pass the initializer(s). For example, when we initialize a vector<int> from single int value, that value might represent the vector's size or it
  345. might be an element value. Similarly, if we supply exactly two int values, those values could be a size and an initial value, or they could be values for a two-element vector. We specify which meaning we inted by whether we use curly braces
  346. or parentheses:
  347. vector<int> v1(10);     //  v1 has ten elements with value 0
  348. vector<int> v2{10};     //  v2 has one element with value 10
  349. vector<int> v3(10, 1);  //  v3 has ten elements with value 1
  350. vector<int> v4{10, 1};  //  v4 has two elements with values 10 and 1
  351.  
  352. We cannot use a range for if the body of the loop adds elements to the vector.
  353.  
  354. #Table 3.5 vector Operations
  355. v.empty()           //  Returns true if v is empty; otherwise returns false.
  356. v.size()            //  Returns the number of elements in v.
  357. v.push_back(t)      //  Adds an element with value t to end of v.
  358. v[n]                //  Returns a reference to the element at position n in v.
  359. v1 = v2             //  Replaces the elements in v1 with a copy of the elements in v2.
  360. v1 = {a,b,c...}     //  Replaces the elements in v1 with a copy of the elements in the comma-separated list.
  361. v1 == v2            //  v1 and v2 are equal if they have the same number of elements and each element in v1 is equal to the corresponding element in v2
  362. v1 != v2            //  v1 cannot be equal to v2
  363. <, <=, >, >=        //  Have their normal meanings using dictionary ordering.
  364.  
  365. The relational operators apply a dictionary ordering: If the vectors have different sizes, but the elements that are in common are equal, then the vector with fewer elements is less than the one with more elements. If the elements have differing values,
  366. then the relationship between the vectors is determined by the relationship between the first elements that differ.
  367. vector<int> v1{1,2,3,4,5,6,7,8,9}
  368. vector<int> v2{2,4,6,8,10}
  369. vector<int> v2{1,2,3,4}
  370. v1 < v2 | v1 > v3 | v2 > v3
  371.  
  372. //  subscript example
  373. //  count the number of grades by clusters of 10: 0--9, 10--19, . .. 90-99, 100
  374. vector<unsigned> scores(11, 0); //  11 buckets, all initially 0
  375. unsigned grade;
  376. while (cin >> grade)        //  read the grades
  377. {
  378.     if (grade <= 100)       //  handle only valid grades
  379.     {
  380.         ++scores[grade/10];     //  increment the counter for the current cluster
  381.     }
  382. }
  383.  
  384. #Iterator
  385. Iterators give us indirect access to an object. We can use an iterator to fetch an element and iterators have operations to move from one element to another.
  386.  
  387. #Table 3.6 Standard Container Iterator Operations
  388. *iter           //  Returns a reference to the element donated by the iterator iter.
  389. iter->mem       //  Dereferences iter and fetches the member named mem from the underlying element. Equivalent to (*iter).mem
  390. ++iter          //  Increments iter to refer to the next element in the container.
  391. --iter          //  Decrements iter to refer to he previous element in the container.
  392. tier1 == iter2  //  Compares two iterators for equality (inequality). Two iterators are equal if they denote the same element or if they are the off-the-end iterator for the same container
  393. iter1 != iter2
  394.  
  395. if (s.begin() != s.end())   //  make sure s is not empty
  396. {
  397.     auto it = s.begin();    //  it denotes the first character in s
  398.     *it = toupper(*it);     //  make that character uppercase
  399. }
  400.  
  401. //  iterator example
  402. for (auto it = s.begin (); it != s.end() && !isspace(*t); ++it)
  403. {
  404.     *it = toupper(*it); //  capitalize the current character
  405. }
  406.  
  407. vectir<int>::iterator it;   //  it can read and write vector<int> elements
  408. string::iterator it2;       //  it2 can read and write characters in a string
  409. vector<int>::const_iterator it3;    //  it3 can read by not write elements
  410. string::const_iterator it4;         //  it4 can read by not write characters
  411.  
  412. vector<int> v;
  413. const vector<int> cv;
  414. auto it1 = v.begin();   //  it1 has the type vector<int>::iterator
  415. auto it2 = cv.begin();  //  it2 has type vector<int>::const_iterator
  416.  
  417. Often this default behavior is not what we want. It is usually best to use a const type (such as a const_iterator) when we need to read but do not need to write to an object. To let us ask specifically for const_iterator type, the new standard
  418. introduced two new functions named cbegin and cend:
  419. auto it3 = v.cbegin();  //  it3 has type vector<int>::const_iterator
  420.  
  421. (*it).empty //  dereferences it and calls the member empty on the resulting object
  422. *it.empty() //  error: attempts to fetch the member named empty from it but it is an iterator and has no member named empty
  423.  
  424. #Table 3.7 Operations supported by vector and string ierators
  425. iter + n            //  Adding (subtracting) an itegral value n to (from) an iterator yields an iterator that many elements forward (backward) within the container. The resulting iterator must denote elements in, or one past the end of,
  426. iter - n            //  the same container.
  427. iter1 += n          //  Compound-assignment for iterator addition and u bsctrion. Assigns iter1 the value of adding n to, or subtracting n from, iter1.
  428. iter1 -= n
  429. iter1 - iter2       //  Subtracting two iterators yields the number that when added to the right-hand iterator yields the left-hand iterator. The iterators must denote elements in, or one past the end of, the same container.
  430. >, >=, <, <=        //  Relational operators in iterators. One iterator is less than another if it referes to an element that appears in the container before the one referred to by the other iterator. The iterators must denote elements in, or one
  431.                     //  past the end of, the same comtainer.
  432.  
  433. //  text must be sorted. beg and end will denote the range we're searching
  434. auto beg = text.begin(), end = text.end();
  435. auto mid = text.begin() + (end - beg) / 2;  //  original midpoint
  436. //  while there are still elements to look at and we haven't found sought
  437. while (mid != end && *mid != sought)
  438. {
  439.     if (sought < *mid)      //  is the element we want in the first half?
  440.     {
  441.         end = mid;          //  if so, adjust the range to ignore the second half
  442.     }
  443.     else                    //  the element we want is in the second half
  444.     {
  445.         beg = mid +1;       //  start looking with the element just after mid
  446.         mid = beg + (end - beg) / 2;    //  new midpoint
  447.     }
  448. }
  449.  
  450. #Array
  451. An array is a container of unnamed objects of a single type that we access by position. Unlike a vector, arrays have fixed size; we cannot add elements to an arrayBecause arrays have fixed size, they sometimes offer better run-time performance
  452. for specialized applicaitons.
  453.  
  454. const unsigned sz = 3;
  455. int ia1[sz] = {0,1,2};          //  array of three ints with values 0, 1, 2
  456. int a2[] = {0, 1, 2};           //  any array of dimension 3
  457. int a3[6] = {0, 1, 2};          //  equivalent to a3[] = {0, 1, 2, 0, 0, 0}
  458. string a4[3] = ("hi", "bye")        //  same as a4[] = {"hi", "bye", ""}
  459. int a5[2] = {0, 1, 2};          //  error: too many initializers
  460.  
  461. #No Copy Or Assignment (on arrays)
  462. We cannot initialize an array as a copy of another array, nor is it legal to assign one array to another;
  463. int a[] = {0, 1, 2};    //  array of three ints
  464. int a2[] = a;           //  error: cannot initialize one array with another
  465. a2 = a;                 //  error: cannot assign one array to another
  466.  
  467. #Understanding Complicated Array Declarations
  468. #Tip: It can be easier to understand array declarations by starting with the array's name and reading them from the inside out.
  469. Like vectors, arrays can hold objects of most any type. For example, we can have an array of pointers. Because an array is an object, we can define both pointers and references to arrays. Defining arrays that hold pointers is fairly
  470. straightforward, defining a pointer or reference to an array is a it more complicated:
  471. int *ptrs[10];      //  ptrs is an array of ten pointers to int
  472. int &refs[10] = /* ? */     //  error: no arrays of references
  473. int (*Parray)[10] = &arr    //  Parray points to an array of ten ints
  474. int (&arrRef)[10] = arr;    //  arrRef refers to an array of ten ints
  475.  
  476. By default, type modfiiers bind right to left. Reading the definition of ptrs from right to left is easy: We see that we're defining an array of size 10, named ptrs, that holds pointers to int.
  477. Reading the definition of Parray from right to left isn't as helpful. Because the array dimension follows the name begin declared, it can be easier to read array declarations from the inside out rather than from right to left. Reading from the
  478. inside out makes it much easier to understand the type of Parray. We start by observing the parentheses around *Parray mean that Parray is a pointer. looking right, we see that Parray points to an array of size 10. Looking left, we see that the
  479. elements in the array are ints. Thus, Parray is a pointer to an array of ten ints. Similary, (&arrRef) says that arrRef is a reference. The type to which it refers is n array of size 10. That array holds elements of type int.
  480.  
  481. int *(&array)[10] = ptrs;   //  array is a reference to an array of ten pointers
  482.  
  483. Reading this declaration from the inside out, we see that array is a reference. Looking right we see that the object to which arry refers to is an array of size 10. Looking left, we see that the element type is pointer to int. Thus, array is a
  484. reference to an array of ten pointers.
  485.  
  486. #3.5.2 Accessing the Elements of an Array
  487. #Tip: When using a variable to subscript an array, we should define that variable to have type size_t. size_t is machine-specificed unsigned type that is guaranteed to be large enough to hold the size of any object in memory.
  488. #     The size_t type is defined in the cstddef header, which is the C++ version of the stddef.h header from the C Library.
  489.  
  490. //  count the number of grades by clusters of 10: 0--9, 10-19, ... 90-99, 100
  491. unsigned scores[11] = {};       //  11 buckets, all value initialized to 0
  492. unsigned grade;
  493. while (cin >> grade)
  494. {
  495.     if (grade <= 100)
  496.     {
  497.         ++scores[grade/10];     //  increment the counter for the current cluster
  498.     }
  499. }
  500.  
  501. for (auto i : scores)   //  for each counter in scores
  502. {
  503.     cout << i << " ";   //  print the value of that counter
  504.     cout << << endl;
  505. }
  506.  
  507. There are various implications of the fact that operations on arrays are often really operations on pointers. One such implication is that when we use an array as an initializer for a varable defined using auto, the deduced type is a pointer, not an array:
  508. int ia[] = {0,1,2,3,4,5,6,7,8,9};   //  ia is an array of ten ints
  509. auto ia2(ia);   //  ia2 is an int* that points to the first element in ia
  510. ia2 = 42;   //  error: ia2 is a pointer, we can't assign an int to a pointer
  511.  
  512. Athough ia is an array of ten ints, when we use ia as an initializer, the compiler treats that initialization as if we had written:
  513. auto ia2(&ia[0]);   //  now it's clear that ia2 h as type int*
  514.  
  515. #Pointers Are Iterators
  516. Pointers that address elements in an array have additional operations beyond those we described in 2.3.2. In particular, pointers to array elements support the same operations as iterators on vectors or strings. For example, we can use the increment
  517. operator to move from one element in an array to the next:
  518. int arr[] = {0,1,2,3,4,5,6,7,8,9}
  519. int *p = arr;   //  p points to the first element in arr
  520. ++p;            //  p points to arr[1]
  521.  
  522. //  traversing an array using pointers
  523. int *e = &arr[10];  //  pointer just past the last element in arr
  524. for (int *b = arr; b != e; ++b)
  525. {
  526.     cout << *b << endl; //  print the elements in arr
  527. }
  528.  
  529. #Pointer Arithmetic
  530. #Pointers that address array elements can use all the iterator operations listed in Table 3.6 and Table 3.7
  531.  
  532. constexpr size_t sz = 5;
  533. int arr[sz] = {1,2,3,4,5};
  534. int *ip = arr;  //  equivalent to int *ip = &arr[0]
  535. int *ip2 = ip + 4;  //  ip2 points to arr[4], the last element in arry
  536.  
  537. //  ok: arr is converted to a pointer to its first element: p points one past the last end of arr
  538. int *p = arr + sz;  //  use caution -- do not dereference
  539. int *p2 = arr + 10; //  error: arr has only 5 elements; p2 is undefined value
  540.  
  541. #ptrdiff_t: A library type that is the result of subtracting two pointers.Machine-specified, defined in the cstdef header, may yield a negative distance so it is a signed integral type.
  542.  
  543. int *p = &ia[2];    //  p points to the element indexed by 2
  544. int j = p[1];       //  p[1] is equivalent to *{p + 1)
  545.                     //  p[1] is the same element as ia[3]
  546. int k = p[-2];      //  p[-2] is the same element as ia[0] //   k = 0
  547. #Warning: Unlike subscripts for vector and string, the index of the built-in subscript operator is not an unsigned type.
  548.  
  549. #3.5.4 C-Style Character Strings
  550. Character string literals are an instance of a more general construct that C++ inherits from C: <C-style character strings>. C-style strings are not a type. Instead, they are a convention for how to represent and use character strings. Strings that follow
  551. this convention are stored in character arrays and are <null terminated>. By null-terminated we mean that the last character in the string is followed by a null character ('\0'). Ordinarily we use pointers to manipulte these strings.
  552.  
  553. #These functions are defined in the cstring header
  554. #Table 3.8 C-Style Character String Functions
  555. strlen(p)           //  Returns the length of p, not counting the null.
  556. strcmp(p1,p2)       //  Compares p1 and p2 for equality. Returns 0 if p1 == p2, a positive value is p1 > p2, a negative value if p1 < p2.
  557. strcat(p1,p2)       //  Appends p2 to p1. Returns p1.
  558. strcpy(p1, p2)      //  Copies p2 inot p1. Returns p1
  559.  
  560. The pointer(s) passed to these routines must point to null-terminated array(s):
  561. char ca[] = {'C', '+', '+'};    //  not null terminated
  562. cout << strlen(ca) << endl;     //  disaster: ca isn't null terminated
  563.  
  564. #Comparing Strings
  565. #Standard C++ library strings
  566. string s1 = "A string example";
  567. string s2 = "A different string";
  568. if (s1 < s2)    //  false: s2 is less than s1
  569.  
  570. #C-style strings
  571. const char ca1[] = "A string example";
  572. const char ca2[] = "A different string";
  573. if (ca1 < ca2)  //  undefined: compares two unrelated addresses
  574. //  this condition actually compares two const char* values. Those pointers do not address the same object, so the comparsion is undefined. You cannot compare to pointers of different arrays.
  575.  
  576. if (strcmp(ca1, ca2) < 0)   //  same effect as string comparison s1 < s2
  577. //  using strcmp to compare the C-style strings. Returns 0 if the strings are equal, or positive or negative value, depending on whether the first string is larger/smaller than the second
  578.  
  579. //  C++ Strings: Concantenting two standard library strings inot one string called largeStr
  580. //  initialize largeStr as a concatenation of s1, a space, and s2
  581. string largeStr = s1 + " " + s2;
  582.  
  583. //  C-Style strings: Concantenting two strings inot an array called largeStr
  584. //  disastrous if we miscalculate the size of largeStr
  585. strcpy(largeStr, ca1);  //  copies ca1 inot largeStr
  586. strcat(largeStr, " ");  //  adds a space at the end of largeStr
  587. strcat(largeStr, cat2); //  concatenates ca2 onot largeStr
  588.  
  589. The problem is that we can easily miscalculate the size needed for largeStr. Moreover, any time we change the values we want to store in largeStr, we have to remember to double-check that we calculate its size correctly. Unfortunately, programs
  590. similar to this code are widely distributed. Programs with such code are error-prone and often lead to serious security leaks.
  591.  
  592. #Mixing Library strings and C-Style Strings
  593. More generally, we can use a null-terminated character array anywhere that we can use a string literal:
  594.     *We can use a null-terminated character array to initialize or assign a string.
  595.     *We can use a null-terminated character array as one operand (but not both operands) to the string addition operator or as the right-hand operand in the string compound assignement (+=) operator.
  596.  
  597. There is no direct way to use a library string when a C-style string is required. There is, however, a string member function named c_str that we can often use to accomplish what we want:
  598. char *str = s;  //  error: can't initialize char* from a string
  599. const char *str = s.c_str();    //  ok
  600.  
  601. #Using an Array to Initialize a vector
  602. In 3.5.1 we noted that we cannot initialize a built-in array from another array. Nor can we initialize an array from a vector. However, we can use an array to initialize a vector. To do so, we specify the address of the first element and
  603. one pas tht elast element that we wish to copy:
  604. int int_arr[] = {0,1,2,3,4,5};
  605. //  ivec has sixe elements; each is a copy of the corrsponding elements in int_arr
  606. vector<int> ivec(begin(int_arr), end(int_arr));
  607.  
  608. The specified range can be a subset of the array:
  609. //  copies three elements: int_arr[1], int_arr[2], int_arr[3]
  610. vector<int> subVec(int_arr + 1, int_arr + 4);
  611.  
  612. This intialization creates subVec with three elements. The values of these elements are copies of the values in int_arr[1] through int_arr[3].
  613.  
  614. #3.6 Multidimensional Arrays
  615. #There are no multidimensional arrays in C++. They are actually arrays of arrays (of arrays of arrays, etc).
  616.  
  617. We define an array whose elements are arrays by providing two dimensions: the dimension of the array itself and the dimension of its elements:
  618. int ia[3][4];   //  array of size 3; each element is an array of ints of size 4
  619. //  array of size 10; each element is a 20-element array whose elements are arrays of 30 ints
  620. int arr[10][20][30] = {0};  //  initialize all elements to 0
  621.  
  622. #Two-dimensional array: The first dimension is usually referred to as the row and the second is the column.
  623.  
  624. int ia[3][4] = {    //  three elements, each element is an array of size 4
  625.     {0,1,2,3},      //  initializers the row indexed by 0
  626.     {4.5.6.7},      //  initializers the row indexed by 1
  627.     {8,9,10,11}     //  initializers for the row index by 2
  628. };
  629.  
  630. As is the case for single-dimensioanl arrays, elements may be left out of the initializer list. We can initialize only the first element of each row as follows:
  631. //  explicitly initialize only element 0 in each row
  632. int ia[3][4] = {{0},{4},{8}};
  633.  
  634. //  assigns the first element of arr to the last element in the last row of ia
  635. ia[2][3] = arr[0][0][0];
  636. int (&row)[4] = ia[1];  //  binds row to the second four-element array in ia
  637.  
  638. //  Pair of nesteed for loops to process the elements in a multidimensional array
  639. constexpr size_t rowCnt = 3, colCnt = 4;
  640. int ia[rowCnt][colCnt]; //  12 uninitialized elements
  641. //  for each row
  642. for (size_t i = 0; i != rowCnt; ++i)
  643. {
  644.     for (size_t j = 0; j!= colCnt; ++j)
  645.     {
  646.         ia[i][j] = i * colCnt + j;
  647.     }
  648. }
  649.  
  650. //  Does the same thing as above except in a range for
  651. for (const auto &row : ia)  //  for every element in the outer array
  652. {
  653.     for (auto col : row)    //  for every element in the inner array
  654.     {
  655.         cout << col << endl;
  656.     }
  657. }
  658.  
  659. The outer for loops through each of the array elements in ia. The inner for loops through the elements of those interior arrays. In this case, we set the value of each element as its index in the overall array.
  660.  
  661. //  Note: To use a multidimensional array in a range for, the loop control variable for all but the inntermost array must be references.
  662.  
  663. With the advent of the new standard, we can often avoid having to write the type of a pointer into an array by using auto or decltype:
  664. //  print the value of each element in ia, with each inner array on its own line
  665. for (auto p = ia; p != ia + 3; ++p)     //  p points to an array of four ints
  666. {
  667.     for (auto q = *p; q != *p + 4; ++q) //  q points ot the first element of an array of four ints; that is, q points to an int
  668.     {
  669.         cout << *q << ' ';
  670.     }
  671.     cout << endl;
  672. }
  673.  
  674. Of course, we can even more easily write this loop using the library begin and end functions:
  675. for (auto p = begin(ia); p != end(ia); ++p)     //  p points to the first in ia
  676. {
  677.     for (auto q = begin(*p); q != end(*p); ++q) //  q points to the first element in an inner array
  678.     {
  679.         cout << *q << ' ';      //  prints the int value to which q points
  680.     }
  681.     cout << endl;
  682. }
  683.  
  684. #Type Aliases Simplify Pointers to Multidimensional Arrays
  685. A type alias can make it easier to read, and understand pointers to multidimensional arrays. For example:
  686. using int_array = int[4];   //  new style type alias declaration
  687. typedef int int_array[4];   //  equivalent typedef declaration
  688. //  print the value of each element in ia, with each inner array on its own life
  689. for (int_array *p = ia; p != ia + 3; ++p)
  690. {
  691.     for (int *q = *p; q != *p + 4; ++q)
  692.     {
  693.         cout << *q << ' ';
  694.     }
  695.     cout << endl;
  696. }
  697.  
  698. /* Chapter 4 */
  699. #4.1.1 Basic Concepts
  700. There are both <unary operators> and <binary operators>. Unary operators, such as address-of (&) and dereference (*), act as one operand. Binary operators, such as equality (==) and multiplication (*), act on two operands. There is also one
  701. ternary operator that takes three operands, and one operator, function call, that takes an unlimited number of operands.
  702.  
  703. #Grouping Operators and Operands
  704. Understand expressions with multiple operators requires understanding the <precedence> and <associativity> of the operators and may depend on the <order of evaluation> of the operands.
  705.  
  706. #Operand Conversions
  707. Operands are often converted from one type to another.
  708. Although the rules are somewhat complicated, for the most part conversions happen in unsuprising ways. For example, we can convert an integer to floating-point, and vice versa, but we cannot convert a pointer type to floating-point. What may
  709. be a bit surprising is that small integral type operands (e.g., bool, char, short, etc) are generally <promoted> to a larger integral type. Typically int.
  710.  
  711. #Lvalues and Rvalues
  712. Every expression in C++ is either an <rvalue> (pronounced "are-value") or an <lvalue> (pronounced "ell-value").
  713. An lvalue expression yields an object or a function. However, some lvalues, such as const objects, may not be the left-hand operand of an assignment. Moreover, some expressions yield objects but return them as rvalues, not lvalues. Roughly
  714. speaking, when we use an object as an rvalue, we use the object's value (its contents). When we use an object as an lvalue, we use the object's identity (its location in memory).
  715.  
  716. Operators differ as to whether they require lvalue or rvalue operands and as to whether they return lvalues or rvalues. The important point is that we can use an lvalue when an rvalue is required, but we cannot use an rvalue when an lvalue (ie.e, a location)
  717. is required. When we use an lvalue in place of an rvalue, the object's contents (its value) are used. We have already used several operators that involve lvalues.
  718.     *Assignment requires a (nonconst) lvalue as its left-hand operand and yields its left-hand operand as an lvalue.
  719.     *The address-of operator requires an lvalue operand and returns a pointer to its operand as an rvalue.
  720.     *The built-in dereference and subscript oeperators and the iterator dereference and string and vector subscript operators all yield lvalues.
  721.     *The built-in and iterator increment and decremenet operators require lvalue operands and the prefix version (which are the ones we have used so far) also yield lvalues.
  722.    
  723. Lvalues and rvalues also differ when used with decltype. When we apply decltype to an expression (other than a variable), the result is a reference type if the expression yields an lvalue. As an example, assume p is an int*. Because dereference
  724. yeilds an lvalue, decltype(*p) is an int&. On the other hand, because the address-of operator yields an rvalue decltype(&p) is int**, that is, a pointer to a pointer to type int.
  725.  
  726. #4.1.2 Precedence and Associativity
  727. An expression with two or more operators is a <compound expression>. Evaluating a compound expression involves grouping the operands to the operators. Precedence and associativity determine how the operands are grouped. That is, they determine
  728. which parts of the expression are the operands for each of the operators in the expression. Programmers can override these rules by parenthesizing compound expression to force a particular grouping.
  729.  
  730. In general, the value of an expression depends on how the subexpressionis are grouped. Operands of operators with higher precedence group more tightly than operands of operators at lower precedence. Associativity determines how to group operands
  731. with the same precedence. For example, multiplication and division have the same precedence as each other, but they have higher precedence than addition. Therefor operands to multiplication and division group before operands to addition and subtraction. The
  732. arithmetic operators are left associative, which means operators at the same precdence group left to right:
  733.     *Because of precedence, the expression 3+4*5 is 23, not 35.
  734.     *Because of associativity, the expression 20-15-3 is 2, not 8.
  735.  
  736. As a more complicated example, a left-to-right evaluation of the following expression yields 20:
  737. 6 + 3 * 4 / 2 + 2
  738.  
  739. Other than imaginable results including 9, 14, and 36. In C++, the result is 14 because this expression is equivalent to
  740. //  parentheses in this expression match default precedence and associativity
  741. ((6 + ((3 * 4) / 2 )) + 2)
  742.  
  743. #Parentheses Override Precedence and Associativity
  744. We can override the normal grouping with parentheses. Parenthesized expressions are evaluted by treating each parenthesized subexpression as a unit and otherwise applying the normal precedence rules. For example, we can parenthesize the expression above
  745. to force the result to be any of the four possible values:
  746. //  parentheses result in alternative groupings
  747. cout << (6 + 3 ) * (4 / 2 + 2) << endl;     //  prints 36
  748. cout << ((6 + 3) * 4) / 2 + 2)  << endl;    //  prints 20
  749. cout << 6 = 3 * 4 / ( 2 + 2) << endl;       //  prints 9
  750.  
  751. #When Precedence and Associativity Matter
  752. We have already seen examples where precedence affects the correctness of our programs. For example, consider the discussion in 3.5.3 about dereference and pointer arithmetic:
  753. int ia[] = {0,2,4,6,8}  //  array of five elements of type int
  754. int last = *(ia+4);     //  initializes last to 8, the value of is[4]
  755. last = *ia +4;          //  last = 4, equivalent to ia[0] + 4
  756.  
  757. If we want to access the element at the location ia+4, then the paentheses around the addition are essential. Without parentheses, *ia is grouped first and 4 is added to the value in *ia.
  758.  
  759. #4.1.3 Order Of Evaluation
  760. For operators that do not specify evaluation order, it is an error for an expression to refer to and change the same object. Expressions that do so have undefined behavior. As a simple example, the << operator makes no guarantees about when or how
  761. its operands are evaluated. As a result, the following output expression is undefined:
  762. int i = 0;
  763. cout << i << " " << ++i << endl;    //  undefined
  764.  
  765. There are four operators that do guarantee the order in which operands are evaluated. We saw in 3.2.3 that the logical AND (&&) operator guarantees that its left-hand operand is evaluated first. Moreover, we are also guaranteed that the right-hand
  766. operand is evaluated only if the left-hand operand is true. The only other operators that guarantee the order in which operands are evaluated are the logical OR (||) operator, the conditional (? :) operator, and the comma (,) operator.
  767.  
  768. #Order of Evaluation, Precedence, and Associativity
  769. Order of operand evaluation is independent of precedence and associativity. In an expression such as f() + g() * h() + j();
  770.     *Precedence guarantees that the results of g() and h() are multiplied.
  771.     *Associativity guarantees that the result of f() is added to the product of g() and h() and that the result of that addition is added to the value of j().
  772.     *There are no guarntees as to the order in which these functions are called.
  773.  
  774. If f, g, h, and j are independent functions that do not affect the state of the same objects or perform IO, then the order in which the functions are called is irrelevant. If any of these functions do affect the same object, then the expression is
  775. in error and has undefined behavior.
  776.  
  777. #4.2 Arithmetic Operators
  778. Table 4.1 (and the operator tables in subsequent sections) groups the operators by their precedence. The unary arithmetic operators have higher precedence than the multiplication and division operators, which in turn have higher precedence
  779. than the binary addition and subtraction operators. Operators of higher precedence group more tightly than do operators with lower precedence. These operators are all left associative, meaning that they group left to right when the precedence
  780. levels are the same.
  781.  
  782. #Table 4.1 Arithmetic Operators (Left Associative)
  783. Operator        Function            Use
  784. +               unary plus          + expr
  785. -               unary minus         - expr
  786. __________________________________________________
  787. *               multiplication      expr * expr
  788. /               division            expr / expr
  789. %               remainder           exper % expr
  790. __________________________________________________
  791. +               addition            expr + expr
  792. -               subtraction         expr - expr
  793.  
  794. The unary plus operator and the addition and subtraction operators may also be applied to pointers. When applied to a pointer or arithmetic value, unary plus returns a (possibly promoted) copy of the value of its operand.
  795. int i = 1024;
  796. int k = -i;     //  i is -1024
  797. bool b = true;
  798. bool b2 = -b;   //  b2 is true!
  799.  
  800. ****Caution: Overflow and Other Arithmetic Exceptions****
  801.     Some arithmetic expressions yield undefined results. Some of these undefined expressions are due to the nature of mathematics-for example, division by zero. Other are undefined due to the nature of computers-for example, due to overflow. Overflow
  802.     happens when a value is computed that is outside the range of values that the type can represent.
  803.    
  804.     Consider a machine on which shorts are 16 bits. In that case, the maximum short is 32767. On such a machine, the following compound assignment overflows:
  805.     short short_value = 32767;  //  max value if shorts are 16 bits
  806.     short_value += 1;           //  this calculation overflows
  807.     cout << "short_value: " << short_value << endl;
  808.    
  809.     The assignment to short_value is undefined. Representing a signed value of 32768 requires 17 bits, but only 16 are available. On many systems, there is no compile-time or run-time warning when an overflow occurs. As iwth any undefined
  810.     behavior, what happens is unpredictable. On our systems the program completes and writes
  811.     short_value: -32768
  812.     The value "wrapped around": the sign bit, which had been 0, was set to 1, resulting in a negative value. On another system the result might be different, or the program might behave differently, including crashing entirely.
  813.  
  814. Division between integers returns an integer. If the quotient contains a fractional part, it is truncated toward zero:
  815. int ival1 = 21/6;   //  ival1 is 3; result is truncated; remainer is discarded
  816. int ival2 = 21/7;   //  ival2 is 3; no remainder; result is an integral value
  817.  
  818. The % operator, known as the "remainder" or the "modulus" operator, computes the remainder that results from dividing the left-hand operand by the right-hand operand. The operands to % must have integral type:
  819. int ival = 42
  820. double dval = 3.14;
  821. ival % 12;  //  ok: result is 6
  822. ival % dval;    //  error: floating-point operand
  823.  
  824. The modulus operator is defined so that if m and n are integers and n is nonzero, then (m/n)*n + m%n is equal to m. By implication, if m%n is nonzero, it has the same sign as m. Earlier versionis of the language permitted m% to have the same sign
  825. as n on implementations in which negative m/n was rounded away from zero, but such implementations are no prohibited. Moreover, except for the obsucure case where -m overflows, (-m)/n and m/(-n) are always equal to -(m/n),m%(-n) is equal to
  826. m%n, and (-m)%n is equal to -(m%n). More concretely:
  827. 21 % 6;     result is 3     21/6;       result is 3
  828. 21 % 7;     result is 0     21/7        result is 3
  829. -21 % -8    result is -5    -21/-8      result is 2
  830. 21 % -5     result is 1     21 / -5     result is -4
  831.  
  832. #Table 4.2 Logical and Relational Operators
  833. Associativity   Operator    Function                Use
  834. Right               !       logical NOT             !expr
  835. ________________________________________________________________
  836. Left                <       less than               expr < expr
  837. Left                <=      less than or equal      expr <= expr
  838. Left                >       greater than            expr > expr
  839. Left                >=      greater than or equal   expr >= expr
  840. _________________________________________________________________
  841. Left                ==      equality                expr == expr
  842. Left                !=      inequality              expr != expr
  843. _________________________________________________________________
  844. Left                &&      logical AND             expr && expr
  845. _________________________________________________________________
  846. Left                ||      logical OR              expr || expr
  847.  
  848. //  print the first element in vec if there is one
  849. if (!vec.empty())
  850. {
  851.     cout << vec[0];
  852. }
  853.  
  854. #The Relation Operators
  855. The relation operators (<, <=, >, >=) have their ordinary meanings and return bool values. These operators are left associative.
  856.  
  857. Because the relational operators return bools, the result of chaining these operators together is likely to be surprising:
  858. //  oops! this condition compares k to the bool result of i < j
  859. if (i < j < k)  //  true if k is greater than 1
  860.  
  861. This condition groups i and j to the first < operator. The bool result of that expression is left-hand operand of the second less-than operator. That is, k is compared to the true/false result of the first comparison! To accomplish the test we intended,
  862. we can rewrite the expression as follows:
  863. //  ok: condition is true if i is smaller than j and j is smaller than k
  864. if (i < j && j < k) { /* ... */ }
  865.  
  866. #4.4 Assignment Operators
  867. Under the new standard we can use a braced initializer list on the right-hand side:
  868. k = {3.14};         //  error: narrowing conversion
  869. vector<int> vi;     //  initially empty
  870. vi = {0,1,2,3,4,5,6,7,8,9}; //  vi now has ten elements, values 0 through 9
  871.  
  872. If the left-hand operand is of a built-in type, the initializer list may contain at most one value, and that value must not require a narrowing conversion.
  873.  
  874. For class types, what happens depends on the details of the class. In the case of vector, the vector template defines its own version of an assignment operator that can take an initailizer list. This operator replaces the elements of the left-hand
  875. side with the elements in the lift on the right-hand side.
  876.  
  877. #Assignment is Right Associative
  878. Unlike the other binary operators, assignment is right associative:
  879. int ival, jval;
  880. ival = jval = 0;    //  ok: each assigned 0
  881.  
  882. Each object in a multiple assignment must have the same type as its right-hand neighbor or a type to which that neighbor can be converted:
  883. int ival, *pval;    //  ival is an int; pval is a pointer to int
  884. ival = *pval = 0;   //  error: cannot assign the value of a pointer to an int
  885. string s1, s2; 
  886. s1 = s2 = "OK";     //  string literal "OK" converted toa  string
  887.  
  888. #Assignment Has Low Precedence
  889. Assignments often occur in conditions. Because assignment has relatively low precedence, we usually must parenthesize the assignment for the condition to work properly. To see why assignment in a condition is useful, consider the following
  890. loop. We want to call a function until it returns a desired value-say, 42:
  891. //  a verbose and therefore more error-prone way to write this loop
  892. int i = get_value();    //  get the first value
  893. while ( i != 42)
  894. {
  895.     //  do something..
  896.     i = get_value();    //  get remaining values
  897. }
  898.  
  899. Here we start by calling get_value followed by a loop whose condition uses the value returned from that call. The last statement in this loop makes another call to get_value, the loop repeats. We can write this code more directly as
  900. int i;
  901. //  a better way to write our loop---what the condition does is no clearer
  902. while ((i = get_value()) != 42)
  903. {
  904.     //  do something...
  905. }
  906.  
  907. #4.2 Increment and Decrement Operators
  908. The increment (++) and decrement (--) operators provide a convenient notational shorthand for adding or subtracting 1 from an object. This notation rises above mere convenience when we use these operators with iterators, because many iterators do not support
  909. arithmetic.
  910.  
  911. There are only two forms of theses operators: prefix and postfix. So far, we have used only the prefix form. This form increments (or decrements) its operand and yields the changed object as a result. The postfix operators increment (or decrement)
  912. the operand but yield a copy of the original, unchaged value as its result:
  913. int i = 0, j;
  914. j = ++i;    //  j = 1, i = 1: prefix yields the incremented value
  915. j = i++;    //  j = 1, i = 2: postfix yields and unincremented value
  916.  
  917. These operators require lvalue operands. The prefix operators return the object itself as an lvalue. The postfix operators return a copy of the object's original value as an rvalue.
  918.  
  919. #Combining Dereference and Increment in a Single Expression
  920. The postfix versions of ++ and -- are used when we want to use the current value of a variable and increment it in a single compound expressioin.
  921.  
  922. As one example, we can use postfix increment to write a loop to print the values in a vector up to but not including the first negative value:
  923. auto pbeg = v.begin();
  924. //  print elements up to the first negative value
  925. while (pbeg != v.end() && *pbeg >= 0)
  926. {
  927.     cout << *pbeg++ << endl;    //  print the current value and advance pbeg
  928. }
  929.  
  930. The expression *pbeg++ is equivalent to *(pbeg++). The subexpression pbeg++ increments pbeg and yields a copy of the previous values of beg as its result. Accordingly, the operand of * is the unincremented value of pbeg. Thus, the statement prints
  931. the element to which pbeg originally pointed and increments pbeg.
  932.  
  933. This usage relies on the fact that postfix increment returns a copy of its original, unincremented operand. If it returned the incremented value, we'd dereference the incremented value, with disastrous results. We'd skip the first element. Worse,
  934. if the sequence had no negative values, we would attempt to dereference one too many elements.
  935.  
  936. //  the behavior of ths follow loop is undefined!
  937. while (beg != s.end() && !isspace(*beg))
  938. {
  939.     *beg = toupper(*beg++); //  error: this assignment is undefined
  940. }
  941. results in undefined behavior. The problem is that in the revised version, botht he left-and right-hand operands use = use beg and the right-hand operand changes beg. The assignment is therefore undefined. The compiler might evaluate the expression as either
  942. *beg = toupper(*beg);   //  execution if left-hand side is evaluted first
  943. *(beg + 1) = toupper(*beg); //  execution if right-hand side is evaluted first
  944. or it might evalute in yet some other way.
  945.  
  946. #4.6 The Member Access Operators
  947. The dot and arrow operators provide for member access The dot operator fetches a member from an object of class type; arrow is defined so that ptr->mem is a synonym for (*ptr).mem:
  948. string s1 = "a string", *p = &s1;
  949. auto n = s1.size(); //  run the size member of the string s1
  950. n = (*p).size();    //  run size on the object to which p points
  951. n = p->size();      //  equivalent to (*p).size()
  952.  
  953. Because dereference has a lower precedence than dot, we must parenthesize the dereference subexpression. If we omit the parentheses, this code means something quite different:
  954. //  run the size member of p, then dereference the result!
  955. *p.size();  //  error: p is a pointer and has no member named size
  956.  
  957. The arrow operator requires a pointer operand and yields an lvalue. The dot operator yields an lvalue if the object from which the member is fetched is an lvalue; otherwise the result is an rvalue.
  958.  
  959. #The Conditional Operator
  960. The condition operator (the <?: operator) lets us embed simple if-else logic inside an expression. The conditional operator has the following form:
  961. cond ? expr : expr;
  962. where cond is an expression that is used as a condition and expr1 and expr2 are expressions of the same type (or types that can be converted to a common type). This operator executes by evaluting cond. If the condision is true, then expr is evaluted;
  963. otherwise, expr2 is evaluted. As one example, we can use a conditional operator to determine whether a grade is pass or fail:
  964. string finalgrade = (grade < 60) ? "fail" : "pass";
  965.  
  966. #Nesting Conditional Operations
  967. We can nest one conditional operator inside another. That is, the conditional operator can be used as the cond or as one or both of the exprs of another conditional expressions. As an example, we'll use a pair of nested conditionals to perform a
  968. three-way test to indicate whether a grade is a high pass, an ordinary pass, or fail:
  969. finalgrade = (grade > 90) ? "high pass" : (grade < 60) ? "fail" : "pass";
  970.  
  971. The first condition checks whether the grade is above 90. If so, the expression after the ? is evaluted, which  yields "high pass". If the condition fails, the : branch is executed, which is itself another conditional expression. This conditional asks
  972. whether the grade is less than 60. if so, the ? branch is evaluated and yields "fail". if not, the : branch returns "pass".
  973.  
  974. The conditional operator is right associative, meaning (as usual) that the operands group right to left. Associativity accounts for the fact that the right-hand conditional-the one that compares grade to 60-forms the : branch of the left-hand
  975. conditional expression.
  976.  
  977. #Using A Conditional Operator In An Output Expression
  978. The conditional operator has fairly low precedence. When we embed a conditional expression in a larger expression, we  usually must parenthesize the conditional subexpression. For example, we often use the conditional operator to print one or
  979. another value, depeneding on the result of a condition. An incompletely parenthesized conditional operator in an output expression can have surprising results:
  980. cout << ((grade < 60) ? "fail" : "pass");   //  prints pass or fail
  981. cout << (grade < 60) ? "fail" : "pass";     //  prints 1 or 0!
  982. cout << grade < 60 ? "fail" : "pass";       //  error: compares cout to 60
  983.  
  984. The second expression uses the comparison between grade and 60 as the operand to the << operator. The value 1 or 0 is printed, depending on whether grade < 60 is true or false. The << operator returns cout, which is tested as the condition for the
  985. conditional operator. That is, the second expression is equivalent to
  986. cout << (grade < 60);   //  prints 1 or 0
  987. cout ? "fail" : "pass"; //  test cout and then yield one of the two literals
  988.                         //  depending on whether cout is true or false
  989.  
  990. The last expression is an error because it is equivalent to
  991. cout << grade;  //  less-than has lower precedence than shift, so print grade first
  992. cout < 60 ? "fail" : "pass";    //  then compare cout to 60!
  993.  
  994. #4.8 The Bitwise Operators
  995. The bitwise operators take operands of integral type that they use as a collection of bits. These operators let us take and set individual bits. We can also use these operators on a library type named bitset (#include <bitset>) that represents
  996. a flexibly sized collection of bits.
  997.  
  998. As usual, if an operand is a "small integer," its value is first promoted to a larger integral type. The operand(s) can be either signed or unsigned.
  999.  
  1000. #Table 4.3 Bitwise Operators (left Associative)
  1001. Operator    Function        Use
  1002. ~           bitwise NOT     ~expr
  1003. __________________________________________
  1004. <<          left shift      expr1 << expr2
  1005. >>          right shift     expr1 >> expr2
  1006. __________________________________________
  1007. &           bitwise AND     exer1 & expr2
  1008. __________________________________________
  1009. ^           bitwise XOR     expr1 ^ expr2
  1010. __________________________________________
  1011. |           bitwise OR      expr1 | expr2
  1012.  
  1013. If the operand is signed and its value is negative, then the way that the "sign bit" is handled in a number of the bitwise operations is machine dependent. Moreover, doing a left shift that changes the value of the sign bit is undefined.
  1014.  
  1015. ****Warning****
  1016.     Because there are no guarantees for how the sign bit is handled, we strongly recommend using unsigned types with the bitwise operators.
  1017.    
  1018. #Bitwise Shift Operators
  1019. We have already used the overloaded versions of the >> and << operators that the IO library defines to do input and output. The built-in meaning of these operators is that they perform a bitwise shift on their operands. They yield a value
  1020. that is a copy of the (possibly promoted) left-hand operand with the bits shifted as directed by the right-hand operand. The right-hand operand must not be a negative and must be a value that is strictly less than the number of bits in
  1021. the result. Otherwise, the operation is undefined. The bits are shifted left (<<) or right (>>). Bits that are shifted off the end are discarded:
  1022. //  These illustrations have the low-order bit on the right
  1023. //  These examples assume char has 8 bits and int has 32
  1024. //  0233 is an octal literal
  1025. unsigned char bits = 0233;  1 0 0 1 1 0 1 1
  1026. bits << 8   //  bits promoted to int and then shifted left by 8 bits
  1027. 0 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 0 | 1 0 0 1 1 0 1 1 | 0 0 0 0 0 0 0 0
  1028. bit s<< 31  //  left shifts 31 bits, left-most bits discarded
  1029. 1 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 0
  1030. bits >> 3   //  right-shift 3 bits, 3 right-most bits discarded
  1031. 0 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 0 | 0 0 0 1 0 0 1 1
  1032.  
  1033. The left-shift operator (the < << operator>) inserts 0-valued bits on the right. The behavior of the right-shift operator (the <>> operator) depends on the type of the left-hand operand: If that operand is unsigned, then the operator inserts 0-valued
  1034. bits on the left; if it is a signed type, the result is implementation defined-either copies of the sign bit or 0-valued bits are inserted on the left.
  1035.  
  1036. #Bitwise NOT Operator
  1037. The bitwise NOT operator (the <~ operator>) generates a new value with the bits of its operand inverted. Each 1 bit is set to 0; each 0 bit is set to 1
  1038.     unsigned char bits = 0227;  1 0 0 1 0 1 1 1
  1039.     ~bits
  1040.     1 1 1 1 1 1 1 | 1 1 1 1 1 1 1 | 1 1 1 1 1 1 1 | 0 1 1 0 1 0 0 0
  1041. Here, our char operand is first promoted to int. Promoting a char to int leaves the value unchanged but adds 0 bits to the high order postions. Thus, promoting bits to int adds 24 high order bits, all of which are 0-valued. The bits
  1042. in the promoted value are inverted.
  1043.  
  1044. #Bitwise AND, OR, XOR Operators
  1045. The AND (&), OR (|), and XOR (^) operators generate new values with the bit pattern composed from its two operands
  1046.     unsigned char b1 = 0145;    0 1 1 0 0 1 0 1
  1047.     unsigned char b2 = 0257;    1 0 1 0 1 1 1 1
  1048.     b1 & b2 24 high-order bits all 0 | 0 0 1 0 0 1 0 1
  1049.     b1 | b2 24 high-order bits all 0 | 1 1 1 0 1 1 1 1
  1050.     b1 ^ b2 24 high-order bits all 0 | 1 1 0 0 1 0 1 0
  1051.  
  1052. For each bit position in the result of the bitwise AND operator (the <& operator>) the bit is 1 if both operands contain 1; otherwise, the result is 0. For the OR ( inclusive or) operator (the <| operator>), the bit is 1 if either or both operands contain
  1053. 1; otherwise the result is 0. For the XOR (exclusive or) operator (the <^ operator>), the bit is 1 if either but not both operands contain 1; otherwise, the result is 0.
  1054.  
  1055. #Using Bitwise Operators
  1056. As an example of using the bitwise operators let's assume a teacher has 30 students in a class. Each week the class is given a pass/fail quiz. We'll track the results of each quiz using one bit per student to represent the pass or fail grade on
  1057. a given test. We might represent each quiz in an unsigned integral value
  1058. unsigned long quiz1 = 0;    //  we'll use this value as a collection of bits
  1059.  
  1060. We define quiz1 as an unsigned long. Thus, quiz1 will have at least 32 bits on any machine. We explicitly initialize quiz1 to ensure that the bits start out with well-defined values.
  1061.  
  1062. The teacher must be able to set and test individual bits. For example, we'd like to be able to set the bit corresponding to student number 27 to indicate that this student passed the quiz. We can indicate that student number 27 passed by creating a value that
  1063. has only bit 27 turend on. If we use bitwise OR that value with quiz1, all the bits except bit 27 will remain unchanged.
  1064.  
  1065. For the purpose of this example, we will count the bits of quiz1 by assigning 0 to the low-order bit, 1 to the next bit, and so on.
  1066.  
  1067. We can obtain a value indicating that student 27 passed by using the left-shift operator and an unsigned long integer literal 1:
  1068. 1UL << 27;  //  generates a value with only bit number 27 set
  1069.  
  1070. 1UL has a 1 in the low-order bit and (at least) 31 zero bits. We specified unsigned long because ints are only guaranteed to have 16 bits, and we need at least 17. This expression shifts the 1 bit left 27 positions inserting 0 bits behind it.
  1071.  
  1072. Next we OR this value with quiz1. Because we want to update the value of quiz1, we use a compound assignment:
  1073. quiz1 |= 1UL << 27; //  indicating studnet number 27 passed
  1074.  
  1075. The |= operator executes analogously to how += does. it is equivalent to
  1076. quiz1 = quiz1 | 1UL << 27;  //  equivalent to quiz1 | = 1UL << 27
  1077.  
  1078. Imagine that the teacher reexamined the quiz and discovered that student 27 actually had failed the test. The teacher must now turn off bit 27. This time we need an integer that has bit 27 turned off and all the other bits turned on. We'll bitwise
  1079. AND this value with quiz1 to turn off just that bit:
  1080. quiz1 &= ~(1UL << 27);  //  student number 27 failed
  1081.  
  1082. We obtain a value with all but bit 27 turned on by inverting our previous value. That value had 0 bits in all but bit 27, which was a 1. Applying the bitwise NOT to that value will turn off bit 27 and turn on all the others. When we bitwise AND
  1083. this value with quiz1, all except bit 27 will remain unchanged.
  1084.  
  1085. Finally we might want to know how the student at position 27 fared:
  1086. bool status = quiz1 & (1UL << 27);  //  how did student number 27 do?
  1087.  
  1088. Here we AND a value that has bit 27 turned on with quiz1. The result is nonzero (i.e. true) if bit 27 of quiz1 is also on; otherwise, it evalutes to zero.
  1089.  
  1090. #Shift Operators (aka IO Operators) Are Left Associative
  1091. Although many programmers never use the bitwise operators directly, most programmers do use overloaded versions of these operators for IO. An overloaded operator has the same precedence and associativity as the built-in version of that operator. Therefore,
  1092. programmers need to understand the precedence and associativity of the shift operators even if they never use them with their built-in meaning.
  1093.  
  1094. Because the shift operators are left associative, the expression
  1095. cout << "hi" << " there" << endl;
  1096. executes as
  1097. ( (cout << "hi") << " there" ) << endl;
  1098.  
  1099. The shift operators have midlevel precedence: lower than the arithmetic operators but higher than the relational, assignment, and conditional operators. These relative precedence levels mean we usually have to use parentheses to force the correct
  1100. grouping of operators with lower precedence.
  1101. cout << 42 + 10;    //  ok: + has higher precedence, so the sum is printed
  1102. cout << (10 < 42);  //  ok: parentheses force intended grouping: prints 1
  1103. cout << 10 < 42;    //  error: attempt to compare cout to 42!
  1104.  
  1105. The last cout is interpreted as
  1106. (cout << 10) < 42;
  1107. which says to "write 10 onto cout and then compare the result of that operation (i.e. cout) to 42."
  1108.  
  1109. #4.9 The sizeof Operator
  1110. The <sizeof> operator returns the size, in bytes, of an expression or a type name. The operator is right associative. The result of sizeof is a constant expression of type size_t. The operator takes one of two forms:
  1111. sizeof (type)
  1112. sizeof expr
  1113.  
  1114. In the second form, sizeof returns the size of the type returned by the given expression. The sizeof operator is unusual in that it does not evalute its operand:
  1115. Sales_data data, *p;
  1116. sizeof(Sales_data); //  size required to hold an object of type Sales_data
  1117. sizeof data;    //  size of data's type, i.e. sizeof(Sales_data)
  1118. sizeof p;   //  size ofa pointer
  1119. sizeof *p;  //  size of the type to which p points, i.e. sizeof(Sales_data)
  1120. sizeof data.revenue;    //  size of the type of Sales_data's revenue member
  1121. sizeof Sales_data::revenue; //  alternative way to get the size of revenue
  1122.  
  1123. Under the new standard, we can use the scope operator to ask the sizeof a member of a class type. Ordinarily we can only access the members of a class through an object of that type. We don't need to supply an object, because sizeof does not
  1124. need to fetch the member to know its size.
  1125.  
  1126. The result of applying sizeof depends in part on the type involved:
  1127.     sizeof char or an expression of type char is guaranteed to be 1.
  1128.     sizeof a reference type returns the size of an object of the reference type.
  1129.     sizeof a pointer returns the size needed to hold a pointer.
  1130.     sizeof a dereferenced pointer returns the size of an object of the type to which the pointer points; the pointer need not be valid.
  1131.     sizeof an array is the size of the entire array. It is equivalent to taking the sizeof the element type times the number of elements in the array. note that sizeof does not convert the array to a pointer.
  1132.     sizeof a string or a vector returns only the size of the fixed part of these types; it does not return the size used by the object's elements.
  1133.    
  1134. Because sizeof returns the size of the entire array, we can determine the number of elements in an array by dividing the array size by the element size:
  1135. //  sizeof(ia)/sizeof(*ia) returns the number of elements in ia
  1136. constexpr size_t sz = sizeof(ia)/sizeof(*ia);
  1137. int arr2[sz];   //  ok sizeof returns a constant expression
  1138.  
  1139. Implicit Conversion: C++ Defines a set of conversions to transform the operands of a different types to one common type. Carried out automatically.
  1140.  
  1141. The implicit conversions among the arithmetic type sare defined to preserve precision, if possible. Most often, if an expression has both integral and floatingpoint operands, the integer is converted to floating-point. In this case, 3 is
  1142. converted to double, floating-point addition is done, and the result is a double.
  1143.  
  1144. int ival = 3.541 + 3;   //  3 is promoted to float; 3.541 + 3 is then converted to int
  1145.  
  1146. #When Implicit Conversions Occurs
  1147. The compiler automatically converts operands in the following Circumstatnces
  1148.     In most expression, values of integral types smaller than int are first promoted to an appropriate larger integral type.
  1149.     In conditions, nonbool expressions are converted to bool.
  1150.     In initialization, the initializer is converted to the type of the variable; in assignment, the right-hand operand is converted to the type of the left-hand.
  1151.     In arithmetic and relational expressions with operands of mixed types, the types are converted to a common type.
  1152.     As we'll see in Chapter 6, conversions also happen during function calls.
  1153.    
  1154. #4.11.1 The Arithmetic Conversions
  1155. The <arithmetic conversions> convert one arithmetic type to another. The results define a hierarch of type conversions in which operands to an operator are converted to the widest type. For example, if one operand is of type long double, then the other
  1156. operand is converted to type long double regardless of what the second type is. More generally, in expressions that mix floating-point and integral values, the integral value is converted to an appropriate floating-point type.
  1157.  
  1158. #Integral Promotions
  1159. The <integral promotions> convert the small integral types to a larger integral type. The types bool, char, signed char, unsigned char, short, and unsigned short are promoted to int if all possible values of that type fit in an int. Otherwise, the
  1160. value is promoted to unsigned int. As we've seen many times, a bool that is false promotes to 0 and true to 1.
  1161.  
  1162. The larger chars types (wchar_t, char16_t, and char32_t) are promoted to the smallest type of int, unsigned int, long, unsigned long, long long, or unsigned long long in which all possible values of that character type fit.
  1163.  
  1164. #Operands of Unsigned Type
  1165. If the operands of an operator have differeing types, those operands are ordinarly converted to a common type. If any operand is an unsigned type, the type to which the operands are converted depends on the relative size of the integral types
  1166. on the machine.
  1167.  
  1168. As usual, integral promotions happen first. If the resulting type(s) match, no further conversion is needed. if both (possibly promoted) operands have the same signedness, then the operand with the smaller type is converted to the larger type.
  1169.  
  1170. When the signedness differs and the type of the unsigned operand is the same as or larger than that of the signed operand, the signed operand is converted to unsigned. For example, given an unsigned int and an int, the int is converted to
  1171. unsigned int. It is worth noting that if the int has a negative value, the result will be converted as described in 2.1.2, with the same results.
  1172.  
  1173. The remaining case is when the signed operand has a larger type than the unsigned operand. In this case, the result is machine dependent. If all values in the unsigned type fit in the larger type, then the unsigned operand is converted to the signed type. If the
  1174. values don't fit, then the signed operand is converted to the unsigned type. For example, if the operands are long and unsigned int, and int and long have the same size, the long will be converted to unsigned int. if the long type has more bits,
  1175. then the unsigned int will be converted to long.
  1176.  
  1177. #Understanding Arithmetic Conversions
  1178. One way to understand the arithmetic conversions is to study lots of examples:
  1179. bool    flag;   char                cval;
  1180. short   sval;   unsigned short      usval;
  1181. int     ival;   unsigned int        uival;
  1182. long    lval;   unsigned long       ulval;
  1183. float   fval;   double              dval;
  1184. 3.14159L + 'a';     //  'a' promoted to int, then that int converted to long double
  1185. dval + ival;        //  ival converted to double
  1186. dval + fval;        //  fval converted to double
  1187. ival = dval;        //  dval converted (by truncation) to int
  1188. flag = dval;        //  if dval is 0, then flag is false, otherwise true
  1189. cval + fval;        //  cval promoted to int, then that int converted to float
  1190. sval + cval;        //  sval and cval promoted to int
  1191. cval + lval;        //  cval converted to long
  1192. ival + ulval;       //  ival converted to unsigned long
  1193. usval + ival;       //  promotion depends on the size of the unsigned short and int
  1194. uival + lval;       //  conversion depends on the size of unsigned int and long
  1195.  
  1196. The converted value is added to the literal. The other interesting case are the last two expressions involving unsigned values. The type of the result in these expressions is machine dependent.
  1197.  
  1198. #4.11.2 Other Implicit Conversions
  1199. In addition to the arithmetic conversions, there are several additional kinds of implicit conversions. These include:
  1200. Array to Pointer Conversions: in most expressions, when we use an array, the array is automatically converted to a pointer to the first element in that array:
  1201. int ia[10]; //  array of ten ints
  1202. int* ip = ia;   //  convert ia to a pointer to the first element
  1203.  
  1204. This conversion is not performed when an array is used with decltype or as the operand of the address-of (&), sizeof, or typeid operators. The conversion is also omitted when we initialize a reference to an array.
  1205.  
  1206. Pointer Conversions: A const int value of 0 and the literal nullptr can be converted to any pointer type. A pointer to any nonconst type can be converted to (const) void*
  1207.  
  1208. Conversion to const: We can convert a pointer to a nonconst type to a pointer to the corresponding const type, similarly for reference. (int i; const int& j = i; const int* p = &i)
  1209.  
  1210. Our programs have already used class-type conversion: We us a class-type conversion when we use a C-style character string where a library string is expected and we read from an istream in a condition:
  1211. string s, t = "a value";    //  character string literal converted to type string
  1212. while (cin >> s)            //  while condition converts cin to bool
  1213.  
  1214. #4.11.3 Explicit Conversions
  1215. Sometimes we want to explicitly force an object to be converted to a different type. For example, we might want to use floating-point division in the following code:
  1216. int i, j;
  1217. double slope = i/j;
  1218.  
  1219. To do so, we'd need a way to explicitily convert i and/or j to double. We use a <cast> to request an explicit conversion.
  1220.  
  1221. #Named Casts
  1222. The cast-name may be one of <static_cast>, <dynamic_cast>, <const_cast>, and <reinterpret_cast>.
  1223. cast-name<type> (expression);
  1224. cast-name determines the type of conversion is performed.
  1225. <type> is the target type of the conversion. If type is a reference, then the result is an lvalue.
  1226. (expression) is the value to tbe cast.
  1227.  
  1228. #static_cast
  1229. Any well-defined type conversion, other than those involving low-level const, can be requested using a static_cast. For example, we can force our expression to use floating-point division by casting one of the operands to double:
  1230. //  cast used to force floating-point division
  1231. double slope = static_cast<double>(j)/i;
  1232. //  slope is type double, j is converted to type double and divided by i (type int)
  1233.  
  1234. static_cast is often used when a larger arithmetic type is assigned toa  smaller type.
  1235.  
  1236. A static_cast is also useful to perform a conversion that the compiler will not generate automatically. For example, we can use a static_cast to retrieve a pointer value that was stored in a void* pointer:
  1237. void* p = &d;   //  ok: address of any nonconst object can be stored in a void*
  1238. //  ok: converts void* back to the original pointer type
  1239. double *dp = static_cast,double*>(p);
  1240.  
  1241. When we store a pointer in a void* and then use a static_cast to cast the pointer back to its original type, we are guaranteed that the pointer value is preserved. That is, the result of the cast will be equal to the original address value. However,
  1242. we must be certain that the type to which we cast the pointer is the actual type of that pointer; if the types do not match, the result is undefined.
  1243.  
  1244. #const_cast
  1245. A const_cast changes only a low-level const in its operand:
  1246. const char *pc;
  1247. char *p = const_cast<char*>(pc);    //  ok: but writing through p is undefined
  1248.  
  1249. Conventionally we say that a cast that converts a const object to a nonconst type "casts away the const." Once we have cast away the const of an object, the compiler will no longer prevent us from writing to that object. If the object was originally
  1250. not a const, using a cast to obtain write access is legal. However, using a const_cast in order to write to a const object is undefined.
  1251.  
  1252. Only a const_cast may be used to change the constness of an expression. Trying to change whether an expression is const with any of the other forms of named cast is a compile-time error. Similary, we cannot use a const_cast to change the type of an expression:
  1253. const char *cp;
  1254. //  error: static_const can't cast away const
  1255. char *q = static_cast<char*>(cp);
  1256. static_cast<string>(cp);    //  ok: converts string literal to string
  1257. const_cast<string>(cp); //  error: const_cast only changes constness
  1258.  
  1259. A const_cast is most useful in the context of overloaded functions.
  1260.  
  1261. #reinterpret_cast
  1262. A reinterpret_cast generally performs a low-level reinterpretation of the bit patters of its operands. As an example, given the following cast
  1263. int *ip;
  1264. char *pc = reinterpret_cast<char*>(ip);
  1265. we must never forget that the actual object addressed by pc is an int, not a character. Any use of pc that assumes it's an ordinary character pointer is likely to fail at run time. For example:
  1266. string str(pc);
  1267. is likely to result in bizarre run-time behavior.
  1268.  
  1269. The use of pc to initailize str is a good example of why reinterpret_cast is dangerous. The problem is that types are changed, yet there are no warnings or errors from the compiler. When we initialized pc with the adddress of an int, there is
  1270. no error or warning from the compiler because we explicitly said the conversion was okay. Any subsequent use of pc will assume that the value it holds is a char*. The compiler has no way of knowing that it actually holds a pointer to an int. Thus, the
  1271. initialization of str with pc is absolutely correct-albeit in this case meaningless or worse! Tracking down the cause of this sort of problem can be proven extremely difficult, especially if the cast of ip to pc occurs in a file separate from the one
  1272. in which pc is used to initialize a string.
  1273.  
  1274. #4.12 Operator Precedence Table
  1275. #Table 4.4 Operator Precedence
  1276. Associativity
  1277. And Operator        Function            Use                         See Page
  1278. L   ::              global scope            ::name                  286
  1279. L   ::              class scope             class:name              88
  1280. L   ::              namespace scope         namespace:name          82
  1281. ______________________________________________________________________________
  1282. L   .               member selectors        object.member           23
  1283. L   ->              member selectors        pointer->member         110
  1284. L   []              subscript               expr[expr]              116
  1285. L   ()              function call           name(expr_list)         23
  1286. L   ()              type construction       type(expr_list)         164
  1287. _______________________________________________________________________________
  1288. R   ++              postfix increment       lvalue++                147
  1289. R   --              postfix decrement       lvalue--                147
  1290. R   typeid          type ID                 typeid(type)            826
  1291. R   typeid          run-time type ID        typeid(expr)            826
  1292. R   explicit cast   type conversion         cast_name<type>(expr)   162
  1293. _______________________________________________________________________________
  1294. R   ++              prefix increment        ++lvalue                147
  1295. R   --              prefix decrement        --value                 147
  1296. R   ~               bitwise NOT             ~expr                   152
  1297. R   !               logical NOT             !expr                   141
  1298. R   -               unary minus             -expr                   140
  1299. R   +               unary plus              +expr                   140
  1300. R   *               derefence               *expr                   53
  1301. R   &               address-of              &lvalue                 52
  1302. R   ()              type conversion         (type)expr              164
  1303. R   sizeof          size of object          sizeof expr             156
  1304. R   sizeof          size of type            sizeof(type)            156
  1305. R   sizeof..        size of parameter pack  sizeof...(name)         700
  1306. R   new             allocate object         new type                458
  1307. R   new[]           allocate array          new type[size]          458
  1308. R   delete          deallocate object       delete expr             460
  1309. R   delete[]        deallocate array        delete[] expr           460
  1310. R   noexcept        can expr throw          noexcept (expr)         780
  1311. _______________________________________________________________________________
  1312. L   ->*             ptr to member select    ptr->*ptr_to_member     837
  1313. L   .*              ptr to member select    obj.*ptr_to_member      837
  1314. _______________________________________________________________________________
  1315. L   *               multiply                expr * expr             139
  1316. L   /               divide                  expr / expr             139
  1317. L   &               modulo (remainder)      expr % expr             139
  1318. _______________________________________________________________________________
  1319. L   +               add                     expr + expr             139
  1320. L   -               subtract                expr - expr             139
  1321. ________________________________________________________________________________
  1322. L   <<              bitwise shift left      expr << expr            152
  1323. L   >>              bitwise shift right     expr >> expr            152
  1324. ________________________________________________________________________________
  1325. L   <               less than               expr < expr             141
  1326. L   <=              less than or equal      expr <= expr            141
  1327. L   >               greater than            expr > expr             141
  1328. L   >=              greater than or equal   expr >= expr            141
  1329. ________________________________________________________________________________
  1330. L   ==              equality                expr == expr            141
  1331. L   !=              inequality              expr != expr            141
  1332. ________________________________________________________________________________
  1333. L   &               bitwise AND             expr & expr             152
  1334. ________________________________________________________________________________
  1335. L   ^               bitwise XOR             expr ^ expr             152
  1336. ________________________________________________________________________________
  1337. L   |               bitwise OR              expr | expr             152
  1338. ________________________________________________________________________________
  1339. L   &&              logical AND             expr && expr            141
  1340. ________________________________________________________________________________
  1341. L   ||              logical OR              expr || expr            141
  1342. ________________________________________________________________________________
  1343. R   ?:              conditional             expr ? expr : expr      151
  1344. ________________________________________________________________________________
  1345. R   =               assignment              lvalue = expr           144
  1346. ________________________________________________________________________________
  1347. R   *=, /=, %=,     compound assign         lvalu += expr, etc      144
  1348. R   +=, -=,                                                         144
  1349. R   <<=, >>=,                                                       144
  1350. R   &=, |=, ^=                                                      144
  1351. ________________________________________________________________________________
  1352. R   throw           throw exception         throw expr              193
  1353. ________________________________________________________________________________
  1354. L   ,               comma                   expr,                   157
  1355.  
  1356. /*Chapter 5*/
  1357. #Null Statements
  1358. The simples statement is the empty statement, also known as a <null statement>. A null statement is a single semicolon:
  1359. ;   //  null statement
  1360.  
  1361. A null statement is useful where the language requires a statement but the program's logic does not. Such usage is common when a loop's work can be done within its condition. For example, we might want to read an input stream, ignoring everything
  1362. we read until we encounter a particular value:
  1363. //  read until hit end-of-file or find an input equal to sought
  1364. while (cin >> s && s != sought)
  1365. ;   //  null statement
  1366.  
  1367. #Beware of Missing or Extraneous Semicolons
  1368. Although an unnecessary null statement is often harmless, an extra semicolon following the condition ina  while or if can drastically alter the programmer's intent. For example, the following code will loop indefinitly:
  1369. //  disaster: extra semicolon: loop body is this null statement
  1370. while (iter != svec.end()) ;    //  the while body is the empty statement
  1371.     ++iter; //  incremenet is not part of the loop
  1372.    
  1373. #Compound Statements (Blocks)
  1374. A <compound statement>, usually referred to as a <block>, is a (possibly empty) sequence of statements and declarations surrounded by a pair of curly braces. A block is a scope. Names introduced inside a block are accessible only in that block
  1375. and in blocks nested inside that block. Names are visible from where they are defined until the end of the (immediately) enclosing block.
  1376.  
  1377. while (val <= 10) {
  1378.     sum += val; //  assigns sum + val to sum
  1379.     ++val   //  add 1 to val
  1380. }
  1381.  
  1382. We also can define an empty block by writing a pair of curlies with no statements. An empty block is equivalent to a null statement:
  1383. while (cin >> s && s != sought)
  1384.     {}  //  empty block
  1385.    
  1386. #5.3.1 The if Statement
  1387. An <if statement> conditionally executes another statement based on whether specified condition is true. There are two forms of the if: one with an else branch and one without. The syntactic form of the simple if is
  1388. if (condition)
  1389.     statement
  1390. else
  1391.     statement2
  1392.    
  1393. #Dangling Else
  1394. When we nest an if inside another if, it is possible that there will be more if branches than else branches. Indeed, our grading program has foure ifs and two elses. The question arises: How do we know to which if a given else belongs?
  1395.  
  1396. This problem, usualy referred to as a <dangling else>, is common to many programming languages that have both if and if else statements. Different languages solve this problem in different ways. In C++ the ambiguity is resolved by specifying that each
  1397. else is matched with the closest preceding unmatched if.
  1398.  
  1399. Programmers sometimes get into trouble when they write code that contains more if than else branches. To illustrate the problem, we'll rewrite the innermost if else that adds a plus or minus using a different set of conditions:
  1400. //  WRONG: execution does NOT match indentation; the else goes with the inner if
  1401. if (grade % 10 >= 3)
  1402.     if (grade % 10 > 7)
  1403.         lettergrade += '+'; //  grades ending in 8 or 9 get a +
  1404. else
  1405.     lettergrade += '-'; //  grades ending in 3, 4, 5, 6 will get a minus!
  1406.    
  1407. The indentation in our code indicates that we intended the else to go witht he outer if-we intended for the else branch to be executed when the grade ends in a digit less than 3. However, despite our intentions, and contrary to the indentation,
  1408. the else branch is part of hte inner if. This code adds a '-' to grades ending in 3 to 7 inclusive! Properly indented to match the actual execution, what we wrote is:
  1409. //  indentation matches the execution path, not the programmer's intent
  1410. if (grade % 10 >= 3)
  1411.     if (grade % 10 > 7)
  1412.         lettergrade += '+'; //  grades ending in 8 or 9 get a +
  1413.     else
  1414.         lettergrade += '-'; //  grades ending in 3, 4, 5, 6 will get a minus!
  1415.        
  1416. #Controlling The Execution Path With Braces
  1417. We can make the else part of the outer if by enclosing the inner if in a block:
  1418. //  add a plus for grades that end in 8 or 9 and a minus for those ending in 0, 1, or 2
  1419. if (grade % 10 >= 3) {
  1420.     if (grade % 10 > 7)
  1421.         lettergrade += '+'; //  grades ending in 8 or 9 get a +
  1422. } else                      //  curlies force the else to go with the outer if
  1423.         lettergrade += '-'; //  grades ending in 0, 1, or 2 will get a minus
  1424.        
  1425. #5.3.2 The switch Statement
  1426. A <switch statement> provides a convenient way of selecting among a (possibly large) number of fixed alternatives.
  1427.  
  1428. A switch statement executes by evaluating the parenthesized expression that follows the switch. That expression may be an initialized varaible declaration. The expression is converted to integral type. The result of the expression is compared with the
  1429. value associated with each case.
  1430.  
  1431. The case keyword and its associated value together are known as the <case label>. case labels must be integral constant expressions:
  1432. char ch = getVal();
  1433. int ival = 42;
  1434. switch(ch) {
  1435.     case 3.14:  //  error: noninteger as case label
  1436.     case ival:  //  error: nonconstant as case label
  1437.     //  ...
  1438. }
  1439.  
  1440. It is an error for any two case labels to have the same value. There is also a special-case label, default, which we cover on page 181.
  1441.  
  1442. #Control Flow within a switch
  1443. It is important to understand that execution flows across case labels. After a case label is matched, exection starts at that label and continues across all the remaining cases or until the program explicitly interrupts it. To avoid execution
  1444. code for subsequent cases, we must explicitly tell the compiler to stop execution. Under most condition, the last statement before the next case label is break.
  1445.  
  1446. However, there are situations where the default switch behavior is exactly what is needed. Each case label can have only a single value, but sometimes we have two or more values that share a common set of actions. In such instances, we omit a
  1447. break statement, allowing the program to fall through multiple case labels.
  1448.  
  1449. For example, we might want to count only the total number of vowels:
  1450. unsigned vowelCnt = 0;
  1451. //  ...
  1452. switch (ch) {
  1453.     //  any occurence of a, e, i , o, or u increments vowlCnt
  1454.     case 'a':
  1455.     case 'e':
  1456.     case 'o':
  1457.     case 'u':
  1458.         ++vowelCnt;
  1459.         break;
  1460. }
  1461.  
  1462. Because C++ programs are free-form, case labels need not appear on a new line. We can emphasize that the cases represent a range of values by listing them all on a single line:
  1463. switch (ch) {
  1464.     //  alternative legal syntax
  1465.     case 'a': case 'e': case 'i': case 'o': case 'u':
  1466.         ++vowelCnt;
  1467.         break;
  1468. }
  1469.  
  1470. #The default Label
  1471. The statements following the default label are executed when no case label matches the value of the switch expression. For example, we might add a counter to track how many nonvowels we read. We'll increment this counter, which we'll
  1472. name otherCnt, in the default case:
  1473.     //  if ch is a vowel, increment the appropriate counter
  1474.     swwitch (ch) {
  1475.         case 'a': case 'e': case 'i': case 'o': case 'u':
  1476.             ++vowelCnt;
  1477.             break;
  1478.         default:
  1479.             ++otherCnt;
  1480.             break;
  1481.     }
  1482.    
  1483. A label may not stand alone; it must preceded a statement or another case label. If a switch ends with a default case that has no work to do, then the default label must be followed by a null statement or an empty block.
  1484.  
  1485. #Variable Definitions inside the Body of a switch
  1486. As we've seen, execution in a switch can jump across case labels. When execution jumps to a particular case, any code that occurred inside the switch before that label is ignored. The fact that code is bypassed raises an interesting
  1487. question: What happens if the code that is skipped includes a variable definition?
  1488.  
  1489. The answer is that it is illegal to jump from a place where a variable with an initializer is out of scope to a place where that variable is in scope:
  1490. case true:
  1491.     //this switch statement is illegal because these initializations might be bypassed
  1492.     string file_name;   //  error: control bypass an implicitly initialized variable
  1493.     int ival = 0;       //  error: control bypasses an explicitly initialized variable
  1494.     int jval;       //  ok: because jval is not initialized
  1495.     break;
  1496. case false:
  1497.     //  ok: jval is in scope but uninitialized
  1498.     jval = next_num();  //  ok: assign a value to jval
  1499.     if (file_name.empty())  //  file_name is in scope but wasn't initialized
  1500.         //  ....
  1501.        
  1502. If thise code were legal, then any time control jumped to the false case, it would bypass the initialization of file_name and ival. Those variables would be in scope. Code following false could use those variables. However, these variables
  1503. would not have been initialized. As a result, the language does not allow us to jump over an initialization if the initialized variable is in scope at the point to which control transfers.
  1504.  
  1505. If we ned to define and initialize a variable for a particular case, we can do so by defining the variable inside a block, thereby ensuring that the variable is out of scope at the point of any subsequent label:
  1506. case true: {
  1507.     //  ok: declaration statemenet within a statement block
  1508.     string file_name = get_file_name();
  1509.     //  ...
  1510. }
  1511. break;
  1512. case false:
  1513.     if (file_name.empty())  //  error: file_name is not in scope
  1514.    
  1515. #5.4.1 The while statement
  1516. A <while statement> repeatedly executes a target statement as long as a condition is true. Its syntactic form is
  1517. while (condition)
  1518.     statement
  1519.    
  1520. #5.4.2 Traditional for Statement
  1521. The syntactic form of the <for statmeent> is:
  1522. for (init-statement condition; expression)
  1523.     statement
  1524.    
  1525. #Multiple Definitions in the for Header
  1526. As in any other declaration, init-statement can define several objects. However, init-statement may only be a single declaration statement. Therefore, all the variables must have the same base type. As one example, we might write a loop to duplicate
  1527. the elements of a vector on the end as follows:
  1528. //  remember tha size of v and stop when we get to the original last element
  1529. for (decltype(v.size()) i = 0, sz = v.size(); i != sz; ++i)
  1530.     v.push_back(v[i]);
  1531.  
  1532. In thise loop we define both the index, i, and the loop control, sz, in init-statement.
  1533.  
  1534. #Omitting Parts of the for Header
  1535. A for header can omit any (or all) of init-statement, condition, or expression.
  1536.  
  1537. We can use a null statement for init-statement when we an initialization is unnecessary.
  1538.  
  1539. #5.4.3 Range for Statement
  1540. The new standard introduced a simpler for statement that can be used to iterate through the elements of a container or another sequence. The syntactic form of the <range for statement> is:
  1541. for (declaration : expression)
  1542.     statement
  1543.    
  1544. In a range for, the value of end() is cached. If we add elements to (or remove them from) the sequence the value of end might be invalidated.
  1545.  
  1546. #5.4.4 The do while Statement
  1547. The <do while statement> is like a while but the condition is tested after the statement body completes. Regardless of the value of hte condition, we execute the loop at least once, the syntactic form is as follows:
  1548. do
  1549.     statement
  1550. while (condition);
  1551.  
  1552. In a do, statement is executed before condition is evaluated. condition cannot be empty. If condition evaluates as false, then the loop terminates; otherwise, the loop is repeated. Variables used in condition must be defined outside the body of the do
  1553. while statement.
  1554.  
  1555. We can write a program that (indefinitely) does sums using a do while:
  1556. //  repeatedly ask the user for a pair of numbers to sum
  1557. string rsp; //  used in the condition; can't be defined inside the do
  1558. do {
  1559.     cout << "Please enter two values: ";
  1560.     int val1 = 0, val2 = 0;
  1561.     cin >> val1 >> val2;
  1562.     cout << "The sum of " << val1 << " and " << val2 << " = " << val1 + val2 << "\n\n"
  1563.          << "more? Enter yes or no: ";
  1564.     cin >> rsp;
  1565. } while (!rsp.empty() && rsp[0] != 'n');
  1566.  
  1567. Because the condition is not evaluated under after the statement or block is executed, the do while loop does not allow variable definitions inside the condition:
  1568. do {
  1569.     //  ...
  1570.     mumble(foo);
  1571. } while (int foo = get_foo());  //  error: declaration in a do condition
  1572.  
  1573. #5.5.1 The break Statement
  1574. A <break statement> terminates the nearest enclosing while, do while, for, or switch statement. Execution resumes at the statement immediately following the terminated statement.
  1575. string buf;
  1576. while (cin >> buf && !buf.empty()) {
  1577.     switch (buf[0]) {
  1578.     case '-':
  1579.         //  process up to the first blank
  1580.         for (auto it = buf.begin() + 1; it != buf.end(); ++it) {
  1581.             if (*it == ' ')
  1582.                 break;  //  #1, leaves the for loop
  1583.                 //  ...
  1584.         }
  1585.         //  break #1 transfers control here
  1586.         //  remaining '-' processing:
  1587.         break;  //  #2, leaves the switch statement
  1588.     case '+';
  1589.         //  ...
  1590.     }   //  end switch
  1591.     //  end of switch: break #2 transfers control here
  1592. }   //  end while
  1593.  
  1594. The break labeled #1 termintes the for loop that follows the hyphen case label. It does not terminate the enclosing switch statement and in fact does not even terminate the processing for the current case. Processing continues with the first
  1595. statement following the for, which might be additional code to handle a hyphen or the break that completes that section.
  1596.  
  1597. The break labeled #2 termiantes the switch but does not terminate the enclosing while loop. Processing continues after that break by executing the condition in the while.
  1598.  
  1599. #5.5.2 The continue Statement
  1600. A <continue statement> terminates the current iteration of the nearest enclosing loop and immediately begins the next iteration. A continue can appear only sidea  for, while, or do while loop, including inside statements or blocks nested
  1601. inside such loops. Like the break statement, a continue inside a nested loop affects only the nearest enclosing loop. Unlike a break, a continue may appear inside a switch only if that switch is embedded inside an iterative statemnt.
  1602.  
  1603. A continue interrupts the current iteration; execution stays inside the loop. In the case of a while or do while, execution continues by evaluating the condition. In the traditional for loop, execution continues by evaluating the condition. In a
  1604. range for, execution continues by initializing the control variable from the next element in the sequence.
  1605.  
  1606. For example, the following loop reads the standard input one word at a time. Only words that begin with an underscore will be procesed. For any other value, we terminate the current iteration and get the next input:
  1607. string buf;
  1608. while (cin >> buf && !buf.empty()) {
  1609.     if (buf[0] != '_')
  1610.         continue;   //  get another input
  1611.     //  still here? the input starts with an underscore; process buf ...
  1612. }
  1613.  
  1614. #5.5.3 The goto Statement
  1615. A <goto statement> provides an unconditional jump from the goto to another statement in the same function.
  1616.  
  1617. The syntactic form of a goto statement is
  1618.     goto label;
  1619. where label is an indentifier that identifies a statement. A <labeled statement> is any statement that is preceded by an identifier by a colon:
  1620. end: return;    //  labeled statement; may be the target of a goto
  1621.  
  1622. Label identifiers are independent of names used for variables and other identifier. Hence, a label may have the same identifier as another entity in the program without interfering with the other uses of that identifier. The goto and labeled
  1623. statmeent to which it transfers control must be in the same function.
  1624.  
  1625. As with a switch statement, a goto cannot transfer control from a point where an initialized variable is out of scope to a point where that variable is in scope:
  1626. //  ...
  1627. goto end;
  1628. int ix = 10;    //  error: goto bypasses an initialized variable definition
  1629. end:
  1630.     //  error: code here could use ix but the goto bypassed its declaration
  1631.     ix = 42;
  1632.    
  1633. A jump backward over an already executed definition is okay. Jumping back into a point before a variable is defined destroys the variable and constructs it again:
  1634. //  backward jump over an initialized variable definition is okay
  1635. begin:
  1636.     int sz = get_size();
  1637.     if (sz <= 0) {
  1638.         goto begin;
  1639.     }
  1640.    
  1641. Here sz is destroyed when the goto executes. It is defined and initialized anew when control passes back through its definition after the jump back to begin.
  1642.  
  1643. #5.6 try Blocks and Exception Handling
  1644. Exceptions are run-time anomalies-such as losing a database connection or encounter unexpected input-that exist outisde the normal functioning of a program. Dealing with anomalous behavior can be one fo the most difficult parts of designing any system.
  1645.  
  1646. Exception handling is generally used when one part of a program detects a problem that it cannot resolve and the problem is such that the detecting part of the program cannot continue. In such cases, the detecting part needs a way to signal
  1647. that something happened and that it cannot continue. morever, the detecting part needs a wayt o signal that problem without knowing what part of the program will deal with the exception conditioni. Having signaled what happened, the detecting part
  1648. stops processing.
  1649.  
  1650. A program that contains code that might raise an exception (usually) has another part to handle whatever happened. For example, if the problem is invalid input, the handling part might ask the user to provide correct input. If the datbase was lost,
  1651. the handling part might alert an operator.
  1652.  
  1653. Exception handling supports this cooperation between the detecting and handling parts of a program. In C++, exception handling involves
  1654.     <throw expression>, which the detecting part uses to indicate that is encountered something it can't andle. We say that a throw <raises> exception.
  1655.     <try blocks>, which the handling part uses to deal with an exception. A try block starts with the keyboard try and ends with one or more <catch clauses>. Exceptions thrown from code executed inside a try block are usually handled by
  1656.         one of the catch clases. Because they "handle" the exception, catch clauses are also known as <exception handlers>.
  1657.     A set of <exception classes> That are used to pass information about what happened between a throw and an associated catch.
  1658.    
  1659. #5.6.1 A throw Expression
  1660. The detecting part of a program uses a throw expression to raise an exception. A throw consists of the keyword throw followed by an expression. The type of the expression determines what kind of exception is thrown. A throw expression is usually
  1661. followed by a semicolon, making it into an expression statement.
  1662.  
  1663. //  first check that item 1 and item2 represent the same book
  1664. if (item1.sibn() == item2.isbn()){
  1665.     cout << item1 + item2 << endl;
  1666.     return 0;   //  indicate success
  1667. }   else {
  1668.     cerr << "Data must refer to the same ISBN" << endl;
  1669.     return -1;  //  indicate failure
  1670. }
  1671.  
  1672. In a more realistic program, the part that adds the objects might be separated from the part that manages the interaction with a user. In this case, we might rewrite the test to throw an exception rather than returning an error indicator:
  1673. //  first check that the data are from the same item
  1674. if (item1.isbn() != item2.isbn())
  1675.     throw runtime_error("Data must refer to same ISBN");
  1676. //  if we're still here, the ISBNs are the same
  1677. cout << item1 + item2 << endl;
  1678.  
  1679. The type runtime_error is one of the standard library exception types and is defined in the stdexcept header. We'll have more to stay about these types in 5.6.3. We must initialize a runtime_error by giving it a string or a C-style character
  1680. string. That string provides additional information about the problem.
  1681.  
  1682. #5.6.2 The try Block
  1683. The general form of a try block is
  1684. try {
  1685.     program-statements
  1686. } catch (exception-declaration) {
  1687.     handler-statements
  1688. } catch (exception-declaration) {
  1689.     handler-statements
  1690. } // ...
  1691.  
  1692. Following the try block is a list of one or more catch clauses. A catch consists of three parts: the keyword catch, the declaration of a (possibly unnamed) object within parentheses (referrred to as an <exception declaration>), and a
  1693. block. When a catch is selected to handle an exception, the associated block is executed. Once that catch finishes, execution continues with the statement immediately following the last catch clause of the try block.
  1694.  
  1695. The program-statements inside the try constitute the normal logic of the program. Like any other blocks, they contain any C++ statment, including declarations. As with any block, variables declared inside a try block are inaccessible outisde
  1696. the block-in particualr, they are not accessible to the catch clause.
  1697.  
  1698. #Writing a Handler
  1699. In the preceding example, we used a throw to avoid adding two Sales_items that represented different books. We imagined that the part of the program that added two Sales_items was separate from the part that communicated with the user. The part
  1700. that interacts with the user might contain code something like the following to handle the exception that was thrown:
  1701. while (cin >> item1 >> item2) {
  1702.     try {
  1703.         //  execute code that will add the two Sales_items
  1704.         //  if the addition fails, the code throws a runtime_error exception
  1705.     } catch (runtime_error err) {
  1706.         //  remind the user that the ISBNs must match and prompt for another pair
  1707.         cout << err.what() << "\nTry again? Enter y or n" << endl;
  1708.         char c;
  1709.         cin >> c;
  1710.         if (!cin || c == 'n')
  1711.             break;
  1712.     }
  1713. }
  1714.  
  1715. The ordinary logic of the program that manages the interaction with the user appears inside the try block. This part of the program is wrapped inside a try because it might throw an exception to type runtime_error.
  1716.  
  1717. This try block has a single catch clause, which handles exceptions of type runtime_error. The statements in the block following hte catch are executed. if code inside the try block throws a runtime_error. Our catch handles the error by printing
  1718. a message and asking the user to indicate whether to continue. If the user enters 'n', then the break is executed and we exit the while. Otheriwse, execution falls through to the closing brace of the while, which transfers control back
  1719. to the while condition for the next iteration.
  1720.  
  1721. The prompt to the user prints the return from err.what(). We know that err has type runtime_error, so we can infer that what is a member function of runtime_error class. Each of the library exception classes defines a member functioned named
  1722. what. These functions take no arguments and return a C-style character string (i.e., a const char*). The what memeber of runtime_error returns a copy of the string used to initialize the particular object. If the code described in the revious
  1723. secition threw an exception, then this catch would print
  1724.     Data must refer to same ISBN
  1725.     Try again? Enter y or n
  1726.    
  1727. #Funcions Are Exited during the Search for a Handler
  1728. In complicated systems, the execution path of a program may pass through multiple try blocks before encountering code that throws an exception. For example, a try block might call a function that contins a try, which calls another function with its
  1729. own try, and so on.
  1730.  
  1731. The search for a handler reverses the call chain. When an exception is throw, the function that threw the exception is searched first. If no matching catch is found, that function terminates. The function that called the one that threw is
  1732. searched next. If no handler is found, that function also exits. That function's caller is searched next, and so on back up to the execution path until a catch of an appropriate type is found.
  1733.  
  1734. If no appropriate catch is found, execution is transferred to a library function named <termiante>. The behavior of that function is system dependent but is guaranteed to stop further execution of the program.
  1735.  
  1736. Exceptions that occur in programs that do not define any try blocks are handled in the same manner: After all, if there are no try blocks, there can be no handlers. If a program has no try blocks and an exception occurs, then terminate
  1737. is called and the program is exited.
  1738.  
  1739. #5.6.3 Standard Exceptions
  1740. The C++ library defines several classes that it uses to report problems encountered in the functions in the standard library. These excpetion classes also intended to be used in the programs we write. These classes are defines in four headers:
  1741.     The exception header defines the most general kind of exception classes named exception. It communicates only that an exception occured but provides no additional information.
  1742.     The stdexcept header defines several general-purpose exception classes, which are listed in Table 5.1
  1743.     The new header defines the bad_alloc exception type, which we cover in 12.1.2.
  1744.     The type_info header defines the bad_cast exception type, which we cover in 19.2.
  1745.  
  1746. #Table 5.1 Standard Exception CLasses Defined in <stdexcept>
  1747. exception           The most general kind of problem
  1748. runtime_error       Problem that can be detected only at run time.
  1749. range_error         Run-time error: result generated outside the range of values that are meaningful
  1750. overflow_error      Run-time error: computations that overflowed.
  1751. underflow_error     Run-time error: computation that underflowed.
  1752. logic_error         Error in the logic of the program
  1753. domain_error        Logic error: argument for which no result exists
  1754. invalid_argument    Logic error: inappropriate argument
  1755. length_error        Logic error: attempt to create an object larger than the maximum size for that type.
  1756. out_of_range        Logic error: used a value outisde the valid range.
  1757.  
  1758. The library exception classes have only a few operations. We can create, copy, and assign objects of any of the exception types.
  1759.  
  1760. We can only default initialize exception, bad_alloc, and bad_cast objects; it is not possible to provide an initalizer for objects of these exceptions.
  1761.  
  1762. The other exception types have the opposite behavior: We can initialize those objects from either a string or a C-style string, but we cannot default initialize them. When we create objects of any of these other exception types, we must supply
  1763. an intialize. That initalize is used to provide additional information about the error that occurred.
  1764.  
  1765. The exception types define only a single operation named what. That function takes no arguments and returns a const char* that points to a C-style character string. The purpose of thise C-style character string is to provide some sort of
  1766. textual description of the exception thrown.
  1767.  
  1768. /* Chapter 6 */
  1769. A function is a block of code with a name. We execute the code by calling the function. A function may take zero or more arguments and (usually) yields a result. Functions can be overloaded, meaning that the same name may refer to several
  1770. different functions.
  1771.  
  1772. #Calling a Function
  1773. A function call does two things: It initializes the function's parameters from the corresponding arguments, and it transfers control to that function. Execution of the valling function is suspended and execution of the called function begins.
  1774.  
  1775. #Parameters and Arguments
  1776. Arguments are the initializers for a function's parameters. The first argument initializes the first parameter, the second argument initializes the second parameter, and so on. Although we know which argument initializes which parameter,
  1777. we have no guarantees about the order in which arguments are evaluated. The compiler is free to evaluate the arguments in whatever order it prefers.
  1778.  
  1779. #Function Parameter List
  1780. A function's parameter list can be empty but cannot be ommited. Typically we define a function with no parameters by writing an empty parameter list. For compatibility with C, we also can use the keyword void to indicate that there are no
  1781. parameters:
  1782. void f1(){ /* ... */ }  //  implicit void parameter list
  1783. void f2(void){ /* ... */ }  //  explicit void parameter list
  1784.  
  1785. Parameter names are optional. However, there is no way to use an unnamed parameter. Therefore, parameters ordinarily have names. Occasionally a function has a parameter that is not used. Such parameters are often left unnamed, to indicate
  1786. that they aren't used. Leaving a parameter unnammed doesn't change the number of arguments that a call must supply. A call must supply an argument for every parameter, even if that parameter isn't used.
  1787.  
  1788. #Function Return Type
  1789. Most types can be used as the return type of a fuction. In particular, the return type can be void, which means that the function does not return a value. However, the return type may not be an arry type or a function type. However, a function
  1790. may return a pointer to an arry or a function. We'll see how to define functions that return poitners (or references) to arrays and how to return pointers to functions.
  1791.  
  1792. #Automatic Objects
  1793. The objects that correspond to ordinary local variables are created when the function's control path passes through the variable's definition. They are destroyed when control passes the end of the block in which the variable is defined. Objects
  1794. that exist only while a block is executing are known as <automatic objects>. After execution exits a block, the values of the automatic objects created in that block are undefined.
  1795.  
  1796. Parameters are automatic objects. Storage for the parameters is allocated when the function begins. Parameters are defined in the scope of the function body. Hence they are destroyed when the function terminates.
  1797.  
  1798. #Local static Objects
  1799. It can be useful to have a local variable whose lifetime continues across calls to the function. We obtain such objects by defining a local variable as static. Each <local static object> is initialized before the first time execution passes
  1800. through the object's definition. Local statics are not destroyed when a function ends; they are destroyed when the program terminates.
  1801.  
  1802. As a trivial example, here is a function that has that counts how many times it is called:
  1803. size_t count_calls()
  1804. {
  1805.     static size_t ctr = 0;  //  value will persist across calls
  1806.     return ++ctr;
  1807. }
  1808.  
  1809. int main()
  1810. {
  1811.     for (size_t i = 0; i!= 10; ++i)
  1812.         cout << count_calls() << endl;
  1813.     return 0;
  1814. }
  1815.  
  1816. #6.1.2 Function Declarations
  1817. Like any other name, the name of a function must be declared before we can use it. As with variables, a function may be defined only once but may be declared multiple times. With one exception that we'll cover in 15.2, we can declare a function
  1818. that is not defined so long as we never use that function.
  1819.  
  1820. A function declaration is just like a function definition except that a declaration has no function body. In a declaration, a semicolon replaces the function body.
  1821.  
  1822. Because a function declaration has no body, there is no need for parameter names. Hence, parameter names are often omitted in a declaration. Although parameter names are not required, they can be used to help users of the function uderstand
  1823. what the function does:
  1824. //  parameter names chosen to indicate that the iteration denotes a range of values to print
  1825. void print(vector<int>::const_iterator beg, vector<int>::const_iterator end);
  1826.  
  1827. These three elements-the return type, function name, and parameter types-describe the function's interface. They specifiy that all the information we need to call the function. Function declarations are also known as the <function protosypte>.
  1828.  
  1829. #Function Declarations Go In Header Files
  1830. Recall that variables are declared in header files and defined in source files. For the same reasons, functions should be declared in header files and defined in source files.
  1831.  
  1832. #Pointer Parameters
  1833. Pointers behave like any other nonreference type. When we copy a pointer, the value of the pointer is copied. After the copy, the two pointers are distinct. However, a pointer also gives us indrect
  1834. access to the object to which that pointer points.
  1835.  
  1836. The same behavior applies to pointer parameters:
  1837. //  function that takes a pointer and sets the pointed-to value to zero
  1838. void reset(int *ip)
  1839. {
  1840.     *ip = 0;    //  changes the value of the object to which ip points
  1841.     ip = 0;     //  changes only the local copy of ip; the argument is unchanged
  1842. }
  1843.  
  1844. After a call to reset, the object to which the argument points will be 0, but the pointer argument itself is unchanged:
  1845. int i = 42;
  1846. reset(&i)       //  changes i but not the address of i
  1847. cout << "i = " << i << endl;
  1848.  
  1849. #6.2.2 Passing Arguments by Reference
  1850. Reference parameters exploit this behavior. They are often used to allow a function to change the value of one or more of its arguments.
  1851.  
  1852. As one example, we can rewrite our reset program from the previous section to take a reference instead of a pointer:
  1853. //  function that takes a reference to an int and sets the given object to zero
  1854. void reset(int &i)  //  i is just another name for the object passed to reset
  1855. {
  1856.     i = 0;  //  changes the value of the object to which i refers
  1857. }
  1858.  
  1859. When we call this version of reset, we pass an object directly; there is no ned to pass its address:
  1860. int j = 42;
  1861. reset(j);   //  j is passed by reference; the value in j is changed
  1862. cout << "j = " << j << endl;    //  prints j = 0
  1863.  
  1864. In this call, the parameter i is just another name for j. Any use of i inside reset is a use of j.
  1865.  
  1866. #Using Reference to Avoid Copies
  1867. It can be inefficient to copy objects of large class types or larger containers. Moreover, some class types (including IO types) cannot be copied. Functions must use reference parameters to operate
  1868. on objects of a type that cnanot be copied.
  1869.  
  1870. //  compare the length of two strings
  1871. bool isShorter(const string &s1, const string &s2)
  1872. {
  1873.     return s1.size() < s2.size();
  1874. }
  1875.  
  1876. #Using Reference Paramters to Return Additional Information
  1877. A fucntion can return only a single value. However, sometimes a function has more than one value to return. Reference parameters let us effectively return multiple restults. As an exmpale, we'll define a function named find_char that will
  1878. return the position of the first occurence of a given character in a string. We'd also like the function to return a count of how many times that character occurs.
  1879.  
  1880. #6.2.3 const Parameters and Arguments
  1881. When we use parameters that are const, it is important to remember the discussion of top-level const from 2.4.3.
  1882.  
  1883. Just as in any other initialization, when we copy an argument to initialize a paramter, top-level consts are ignored. As a result, top-level const on paramteres are ignored. We can pass either a const or a nonconst object to a parameter
  1884. that has a top-level const:
  1885. void fcn(const int i) { /* fcn can read but not write to i */ }
  1886.  
  1887. When we call fcn passing it either a const int or a plain int. The fact that top-level consts are ignored on paramter has one possibly suprising implication:
  1888. void fcn(const int i) { /* fcn can read but not write to i */ }
  1889. void fcn(int i) { /* ... */ }   //  error redefines fcn(int)
  1890.  
  1891. #Pointer or Reference Parameter and const
  1892. Because parameters are initialized in the same way that variables are initialized, it can be helpful to remember the general initializiation rules. We can initialize an object with a low-level const from a nonconst object but not vice versa,
  1893. and a plain reference must be initialized from an object of the same type
  1894.  
  1895. Exactly the same initialization rules apply to parameter passing:
  1896. int i = 0;
  1897. const int ci = i;
  1898. string::size_type ctr = 0;
  1899. reset(&i);  //  calls the version of reset that has an int* parameter
  1900. reset(&ci); //  error: can't initialize an int* from a pointer to a const int object
  1901. reset(i);   //  calls the version of reset that has an int& parameter
  1902. reset(ci);  //  error: can't bind a plain reference to the const object ci
  1903. reset(42);  //  error: can't bind a plain reference to a literal
  1904. reset(ctr); //  error: types don't match; ctr has an unsigned type
  1905. find_char("Hello World!", 'o', ctr);    //  ok: find_char's first parameter is a reference to const
  1906.  
  1907. #6.2.4 Array Parameters
  1908. Arrays have two special properites that affect how we define and use functions that operate on arrays: We cannot copy an array, and when we use an array it is (usually) converted to a pointer. Because we cannot copy an array, we cannot pass
  1909. an array by value. Because arrays are converted to pointers, when we pass an array to a function, we are actually passing a pointer to the array's first element.
  1910.  
  1911. Even though we cannot pass an array by value, we can write a paramter that looks like an array:
  1912. //  despite appearances, these three declarations of print are equal
  1913. //  each function has a single parmater of type const int*
  1914. void print(const int*);
  1915. void print(const int[]);    //  shows the intent that the function takes an array
  1916. void print(const int[10]);  //  dimension for documentation purpose (at best)
  1917.  
  1918. Regardless of appearances, these declarations are equivalent: Each declares a function with a single parameter of type const int*. When the compiler checks a coll to print, it checks only that the argument has type const int*:
  1919. int i = 0, j[2] = {0, 1};
  1920. print(&i);  //  ok: &i is int *
  1921. print (j);  //  ok: j is converted to an int* that points to j[0]
  1922.  
  1923. If we pass an array to print, that argument is automatically converted to a pointer to the first element in the array; the size of the array is irrelevent.
  1924.  
  1925. #Using a Marker to Specify the Extend of an Array
  1926. The first approach to managing array argumnets requires the array itself to contain an end marker. C-style character strings are an example of this approach. C-style strings are stored in character arrays in which the last character of the string
  1927. is followed by a null character. Functions that deal with C-style strings stop processing the array when they see a null character:
  1928. void print(const char *cp)
  1929. {
  1930.     if (cp) //  if cp is not a null character
  1931.         while (*cp) //  so long as the character it points to is not a null character
  1932.             cout << *cp++;
  1933. }
  1934.  
  1935. #Using the Standard Library Conventions
  1936. A second technique used to manage array arguments is to pass pointers to the first and one past the last element in the array. This approach is inspired by techniques used in the standard library. We'll learn more about this style of programming
  1937. in Part II. Using this approach, we'll print the elements in an array as follows:
  1938. void print(const int *beg, const int *end)
  1939. {
  1940.     //  print every element starting at beg up to but not including end
  1941.     while (beg != end)
  1942.         cout << *beg++ << endl; //  print the current element and advance the pointer
  1943. }
  1944.  
  1945. The while uses the dereference and postfix increment operators to print the current element and advance beg one element at a time through the array. The loop stops when beg is equal to end.
  1946.  
  1947. To call this function, we pass two pointers-one to the first element we want to print and one past the last element:
  1948. int j[2] = {0, 1}
  1949. //  j is converted to a pointer to the first element in j
  1950. //  the second argument is a pointer to one past the end of j
  1951. print(begin(j), end(j));    //  begin and end functions
  1952.  
  1953. #Explicitly Passing a Size Paramter
  1954. A third approach for array arguments, which is common in C programs and older C++ programs, is to define a second paramter that indicates the size of the array. Using this approach, we'll rewrite print as follows:
  1955. //  const int ia[] is equivalent to const int *ia
  1956. //  size is passed explicitly and used to control access to elements of ia
  1957. void print(const int ia[], size_t size)
  1958. {
  1959.     for (size_t i = 0; i != size; ++i){
  1960.         cout << ia[i] << endl;
  1961.     }
  1962. }
  1963.  
  1964. This version uses the size parameter to determine how many elements there are to print. When we call print, we must pass this additional parameter:
  1965. int j[] = {0, 1};   //  int array of size 2
  1966. print(j, end(j) - begin(j));
  1967.  
  1968. #Array Referene Parameters
  1969. Just as we can define a variable that is a reference to an array, we can define a parameter that is a reference to an array. As usual, the reference parameter is bound to the corresponding argument, which in this case is an array:
  1970. //  ok: parameter is a reference to an array; the dimension is part of the type
  1971. void print(int (&arr)[10])
  1972. {
  1973.     for auto (elem : arr)
  1974.         cout << elem << endl;
  1975. }
  1976.  
  1977. ***Note****
  1978.     The parentheses around &arr are necessary.
  1979.     f(int &arr[10]) //  error: declares arr as an array of referenes
  1980.     f(int (&arr)[10])   //  ok: arr is a reference to an array of ten ints
  1981.    
  1982. Because the size of an array is part of its type, it is safe to rely on the dimension in the body of the function. However, the fact that the size is part of the type limits the usefulness of this version of print. We may call this function
  1983. only for an array of exactly ten ints.
  1984.  
  1985. #Passing a Multidimensional Array
  1986. Recall that there are no multidimesional arrays in C++. Instead, what appears to be multidimensional array is n array of arrays.
  1987.  
  1988. As with any array, a multidimensional array is passed as a pointer to its first element. Because we are dealing with an array of arrays, that eleemnt is an array, so the pointer is a pointer to an array. The size of the second (and any
  1989. subsequent) dimension is part of the element type and must be specified:
  1990. //  matrix points to the first element in an array whose elements are arrays of ten ints
  1991. void print(int (*matrix)[10], int rowSize) { /* ... */ }
  1992. declares matrix as a pointer to an array of ten ints.
  1993.  
  1994. We can also define our function using an array syntax. As usual, the compiler ignores the first dimension, so it is best not to include it:
  1995. //  equivalent definition
  1996. void print(int matrix[][10], int rowSize) { /* ... */ }
  1997. declares matrix to be what looks like a two-dimensional array. In fact, the parameter is a poitner to an array of ten ints.
  1998.  
  1999. #6.2.5 main: Handling Command-Line Options
  2000. It turns out that main is a good example of how C++ programs pass arrays to functions. Up to now, we have defined main with an empty parameter list:
  2001. int main() { ... }
  2002.  
  2003. However, we sometimes need to pass arguments to main. The most common arguments to main is to let the user specify a set of options to guide the operation of the program. For example, assuming our main program is an executable file named
  2004. prog, we might pass options to the program as follows:
  2005. prog -d -o ofile data0
  2006.  
  2007. Such command-line options are passed to main in two (optional parameters):
  2008. int main(int argc, char *argv[]) { ... }
  2009.  
  2010. The second parameter, argv, is an arry of pointers to C-style character strings. The first parameter, argc, passes the number of strings in that array. Because the second parameter is an arry, we might alternatively define main as
  2011. int main(int argc, char **argv) { ... }
  2012. indicating that argv points to a char*.
  2013.  
  2014. When arguments are passed to main, the first element in argv points either to the name of the program or to the empty string. Subsequent elements pass the arguments provided on the command line. The element just past the last pointer is guaranteed
  2015. to be 0.
  2016.  
  2017. Given the previous command line, argc would be 5, and argv would hold the following C-style character string:
  2018. argv[0] = "prog";   //  or argv[0] might point to an empty string
  2019. argv[1] = "-d";
  2020. argv[2] = "-o";
  2021. argv[3] = "ofile";
  2022. argv[4] = "data0";
  2023. argv[5] = 0;
  2024.  
  2025. #6.2.6 Functions with Varying Parameters
  2026. Sometimes we do not know in advance how many arguments we need to pass to a function. For example, we might want to write a routine to print error messages generated from our program. We'd like to use a single function to print these error
  2027. messages in order to hnalde them in a uniform way. However, different calls to our error-printing function might pass different arguments, corresponding to different kinds of error messages.
  2028.  
  2029. The new standard provides two primary ways to write a function that takes a varying number of argumnets: If all the arguments have the same type, we can pass a library type named initializer_list. If the argument types vary, we can write a
  2030. special kind of function, known as a variadic template, which we'll cover in 16.4.
  2031.  
  2032. C++ Also have a speical parameter type, ellipsis, that can be used to pass a varying number of arguments. We'll look briefly at ellipsis parameters in this section. However, it is worth noting that this facility ordinarly should be used only
  2033. in programs that need to interface to C functions.
  2034.  
  2035. #Initializer_list Parameters
  2036. We can write a function that takes an unknown number of arguments of a single type by using an initializer_list parameter. An initializer_list is a library type that represents an array of values of the specified type. This type is defined in the
  2037. initializer_list header. The operations that initializer_list provides are listed in Table 6.1.
  2038.  
  2039. #Table 6.1 Operations on initializer-lists
  2040. initializer_list<T> lst;            //  default initializer; an empty list of elements of type T
  2041. iniailizer_list<T> lst{a,b,c...}    //  lst has as many elements as there are initializers; elements are copies of the corresponding initailizers. Elements in the list are const
  2042. lst2(lst)       //  copying or assigning an intializer_list does not copy the elements
  2043. lst2 = lst      //  in the list. After the copy, the original and the copy share the elements.
  2044. lst.size()      //  Number of elements in the list.
  2045. lst.begin()     //  Retruns a pointer to the first and one past the last element in lst
  2046. lst.end()
  2047.  
  2048. Like a vector, initailizer_list is a template. When we define an initializer_list, we must specify the type of the elements that the list will contain:
  2049. initializer_list<string> ls;    //  initializer_list of strings
  2050. initailizer_list<int> l1;       //  initializer_list of ints
  2051.  
  2052. Unlike vector, the elements in an initailizer_list are always const values; there is no way to change the value of an element in an initializer_list.
  2053.  
  2054. We can write our function to produce error messages from a varying number of arguments as follows:
  2055. void error_msg(initializer_list<string> il)
  2056. {
  2057.     for (auto beg = il.begin() ; beg != il.end(); ++beg)
  2058.         cout << *beg << " " ;
  2059.     cout << endl;
  2060. }
  2061.  
  2062. The begin and end operations on initializer_list objects are analogues to the corresponding vector members. The begin() member gives us a pointer to the first element in list, the end() is an off-the-end pointer one past the last
  2063. element. Our function initailizes beg to denote the first element and iterates through each element in the initializer_list. In the body of the loop we dereference beg in order to access the current element and print its value.
  2064.  
  2065. When we pass a sequence of values to an initializer_list parameter, we must enclose the sequence in curly braces:
  2066. //  expected, actual are strings
  2067. if (expected != actual)
  2068.     error_msg({"functionX", expected, actual});
  2069. else
  2070.     error_msg({"functionX", "okay"});
  2071.    
  2072. Here we're calling the same function error_msg, passing three values in the first call and two values in the second.
  2073.  
  2074. A function with an initializer_list parameter can have other parameters as well. For example, our debugging system might have a class, named ErrCode, that represents various kinds of errors. We can revise our program to take an ErrCode
  2075. in addition to an initializer_list as follows:
  2076. void error_msg(ErrCode e, initializer_list<string> il)
  2077. {
  2078.     cout << e.msg() << " : ";
  2079.     for (const auto &elem : il)
  2080.         cout << elem << " ";
  2081.     cout << endl;
  2082. }
  2083.  
  2084. To call this version, we need to revise our calls to pass an ErrCode argument:
  2085. if (expected != actual)
  2086.     error_msg(ErrCode(42), {"functionX", expected, actual});
  2087. else
  2088.     error_msg(ErrCode(0), {"FunctionX", "okay"});
  2089.    
  2090. #Ellipsis Parameters
  2091. Ellipsis parameters are in C++ to allow programs to interface to C code that uses a C library facility named varargs. Generally an ellipsis parameter should not be used for other purposes. Your C compiler documentation will describe how
  2092. to use varargs.
  2093.  
  2094. An ellipsis parameter may appear only as the last elemnt in a parameter list and may take either two forms:
  2095. void foo(parm_list, ...):
  2096. void foo(...);
  2097.  
  2098. #How Values Are Returned
  2099. Values are returned in exactly the same way as variables and parameters are initialized: The return value is used to initialize a temporay at the call site, and that temporar is the result of the
  2100. function call.
  2101.  
  2102. It is important to keep in mind the initialization rules in functions that return local variables. As an exmple, we might write a function that, given a counter, a word, and an ending, gives us back
  2103. the plural version of the word if the counter is greater than 1:
  2104. //  return the plural version of word if ctr is greater than 1
  2105. string make_plural(size_t ctr, const string &word, const string &ending)
  2106. {
  2107.     return (ctr > 1) ? word + ending : word;
  2108. }
  2109.  
  2110. The return type of this function is string, which means the return value is copied to the call site. This function returns a copy of word, or it returns an unnamed temporary string that results from
  2111. adding word and ending.
  2112.  
  2113. As with any other reference, when a function returns a reference, that reference is just another name for the object to which it refers. As an example, consider a function that returns a reference
  2114. to the shorter of its two string parameters:
  2115. //  return a reference to the shorter of two stringstream
  2116. const string &shorterString(const string &s1, const string &s2)
  2117. {
  2118.     return s1.size() < s2.size() ? s1 : s2;
  2119. }
  2120.  
  2121. The parameters and return type are references to const string. The strings are not copied when the function is called or when the result is returned.
  2122.  
  2123. #Never Return a Reference or Pointer to a local Object
  2124. When a function completes, its storage is freed. After a function terminates, references to local objects refer to memory that is no longer valid:
  2125. //  disaster: this function returns a reference to a local object
  2126. const string &mainip()
  2127. {
  2128.     string ret;
  2129.     //  transform ret in some way
  2130.     if (!ret.empty())
  2131.         return ret; //  WRONG: returning a reference to a local object!
  2132.     else
  2133.         return "Empty"; //  WRONG: "Empty" is a local temporary string
  2134. }
  2135.  
  2136. Both of these return statements return an undefined value-what happens if we try to use the value returned from mainip is undefined. In the first return, it should be obvious that the function returns
  2137. a reference to a local object. In the second case, the string literal is converted to a local temporary string object. That object, like the string named s, is local to manip. The storage in which
  2138. temporary resides is freed when the function ends. Both returns refer to memory that is no longer available.
  2139.  
  2140. #Functions That Return Class Types and the Call Operator
  2141. Like any operator the call operator has associativity and precedence. The call operator has the same precedence as the dot and arrow operators. Like those operators, the call operator is left associative. As
  2142. a result, if a function returns a pointer, reference or object of class type, we can use the result of a call to call a member of the resulting object.
  2143.  
  2144. For example, we can determine the size of the shorter string as follows:
  2145. //  call the size of the string returned by shorterString
  2146. auto sz = shorterString(s1, s2).size();
  2147.  
  2148. Because these operators are left associative, the result of shorterString is the left-hand operand of the dot operator. That operator fetches the size member of that string. That memeber is the
  2149. left-hand operand of the second call operator.
  2150.  
  2151. #Reference Returns are Lvalues
  2152. Whether a function call is an lvalue depends on the return type of the function. Calls to functions that return references are lvalues; other return types yield rvalues. A call to a function
  2153. that returns a reference can be used in the same ways as any other lvalue. In particular, we can assign to the result of a function that returns a reference to nonconst:
  2154. char &get_val(string &str, string::size_type ix)
  2155. {
  2156.     return str[ix]; //  get_val assumes the given index is valid
  2157. }
  2158. int main()
  2159. {
  2160.     string s("a value");
  2161.     cout << s << endl;  //  prints a value
  2162.     get_val(s,0) = 'A'; //  changes s[0] to A
  2163.     cout << s << endl;  //  prints A value
  2164.     return 0;
  2165. }
  2166.  
  2167. It may be surprising to see a function call on the left-hand side of an assignment. The return value is a reference, so the call is an lvalue. Like any other lvalue, it may appear as the left-hand
  2168. operand of the assignment operator.
  2169.  
  2170. If the return type is a reference to const, then (as usual) we may not assign to the result of the call:
  2171. shorterString("hi", "bye") = "x";   //  error: return value is const
  2172.  
  2173. #6.3.3 Returning a Pointer to an Array
  2174. Because we cannot copy an array, a function cannot return an array. However, a function can return a pointer or a reference to an array. Unfortunately, the syntax used to define function that return pointers or references to
  2175. arrays can be intimidating. Fortunately, there are ways to simplify such delarations. The most straightforward way is to use a type alias:
  2176. typedef int arrT[10];   //  arrT is a synonym for the type array of ten ints
  2177. using arrtT = int[10];  //  equivalent declaration of arrT; see 2.5.1 (p 68)
  2178. arrT* func(int i);      //  func returns a pointer to an array of ten ints
  2179.  
  2180. Here arrT is a synonym for an array of ten ints. Because we cannot return an array, we define the return type as a pointer to this type. Thus, func is a function that takes a single int argument and returns a pointer to an array of ten ints.
  2181.  
  2182. #Declaring a Function That Returns a Pointer to an Array
  2183. To declare func without using a type alias, we must remember that the dimension of an array follows the name being defined:
  2184. int arr[10];    //  arr is an arry of ten ints
  2185. int *pi[10];    //  p1 is an arry of ten pointers
  2186. int (*p2)[10] = &arr;   //  p2 points to an array of ten ints
  2187.  
  2188. As with these declarations, if we want to define a function that returns a pointer to an array, the dimension must follow the functions name. However, a function includes a parameter list, which also follow the name. The parameter list precedes
  2189. the dimension. Hence, the form of a function that returns a pointer to an array is:
  2190. Type (*function(parameter_list))[dimension]
  2191.  
  2192. As in any other array declaration, Type is the type of the elements and dimension is the size of the array. The parentheses around (*funcion (parmater_list)) are necessary for the same reason that they were required when we defined p2. Without
  2193. them, we be defining a function that returns an array of pointers.
  2194.  
  2195. As a concrete example, the following declares func without using a type alias:
  2196. int (*func(int i))[10];
  2197.  
  2198. To understand this declaration, it can be helpful to think about it as follows:
  2199. -func(int) says that we can call func with an int argument
  2200. -(*func(int)) says we can dereference the result of that call
  2201. -(*func(int))[10] says that dereference the result of a call to func yields an array of size ten.
  2202. -int (*func(int))[10] says the element type in that array is int.
  2203.  
  2204. #Using a Trailing Return Type
  2205. Under the new standard, another way to simplify the declaration of func is by using a <trailing return type>. Trailing returns can be defined for any function, but are most useful for function with complicated return types, such as pointers
  2206. (or references) to arrays. A trailing return type follows the parameter list and is preceded by ->. To signal that the return follows the parameter list, we use auto where the return type ordinarly appears
  2207. //  fcn takes an int argument and returns a pointer to an array of ten ints
  2208. auto func(int i) -> int(*)[10];
  2209.  
  2210. Because the return type comes after the parameter list, it is easier to see that func returns a pointer and that that pointer points to an array of ten ints.
  2211.  
  2212. #Using decltype
  2213. As another alternative, if we know the array(s) to which our function can return a pointer, we can use a decltype to declare the return type. For example, the following function returns a pointer to one of two arrays, deepending on the value
  2214. of its parameter:
  2215. int odd[] = {1,3,5,7,9};
  2216. int even[] = {0,2,4,6,8};
  2217. //  returns a pointer to an array of five int elements
  2218. decltype(odd) *arrPtr(int i)
  2219. {
  2220.     return (i % 2) ? &odd : &even;  //  returns a pointer to the array
  2221. }
  2222.  
  2223. The return type for arrPtr uses decltype to say that the function returns a pointer to whatever type odd has. That object is an array, so arrPtr returns a pointer to an array of five ints. The only tricky part is that we must remember
  2224. that decltype does not automatically convert an array to its corresponding pointer type. The type returned by delctype is an array type, to which we must add a * to indicate that arrPtr returns a pointer.
  2225.  
  2226. #6.4 Overloaded Functions
  2227. Functions that have the same name but different parameter lists and tha appear in the same scope are <overloaded>. For example, in 6.2.4 we defined several functions named print:
  2228. void print(const char *cp);
  2229. void print(const int *beg, const int *end);
  2230. void print(const int ia[], size_t size);
  2231.  
  2232. These functions perform the same general action but apply to different parameter types. When we call these functions, the compiler can deduce which function we want based on the argument type we pass:
  2233. int j[2] = {0, 1};
  2234. print("Hello World");   //  calls print(const char*)
  2235. print(j, end(j) - begin(j));    //  calls print(const int*, size_t)
  2236. print(begin(j), end(j));    //  calls rpint(const int*, const int*)
  2237.  
  2238. Defining Overloaded functions
  2239. Consider a database application with several functions to find a record based on name, phone number, account number, and so on. Function overloaded lets us define a collection of functions, each named lookup, that differ in terms of how they
  2240. do the search. We can call lookup passing a value of any of several types:
  2241. Record lookup(const Account&);  //  find by Account
  2242. Record lookup(const Phone&);    //  find by Phone
  2243. Record lookup(const Name&); //  find by Name
  2244.  
  2245. Account acct;
  2246. Phone phone;
  2247. Record r1 = lookup(acct);   //  call version that takes an Account
  2248. Record r2 = lookup(phone);  //  call version that takes a Phone
  2249.  
  2250. Overloaded functions must differ in the number or the type(s) of their parameters. Each of the functions above takes a single parameter, but the parameters have different types.
  2251.  
  2252. It is an error for two functions to differ only in terms of their return types. If the parameter lists of two functions match but the return types differ, then the second declaration is an error.:
  2253. Record lookup(const Account&);
  2254. bool lookup(const Account&);    //  error: only the return type is different
  2255.  
  2256. #Determining Wheter Two Parameter Types Differ
  2257. Two parameter lists can be identical, even if they don't look the same:
  2258. //  each par declares the same function
  2259. Record lookup(const Account &acct);
  2260. Record lookup(const Account&);  //  parameter names are ignored
  2261.  
  2262. typdef Phone Telno;
  2263. Record lookup(const Phone&);
  2264. Record lookup(const Telno&);    //  Telno and Pone are the same type
  2265.  
  2266. In the first pair, the first declaration names its parameter. Parameter names are only a documentation aid. They do not change the parameter list.
  2267.  
  2268. In the second pair, it looks like the types are different, but Telno is not a new type; it is a synonym for Phone. A type alias provides an alternate name for an exisiting type; it does not create a new type. Therefore, two parameters that
  2269. differ only in that one uses an alias and the other uses the type to which the alias correspondings are not different.
  2270.  
  2271. #Overloading and const Parameters
  2272. We saw in 6.2.3, top-level const has no effect on the objects that can be passed to the function. A parameter that has top-level const is indistinguishable from one without a top-level const:
  2273. Record lookup(Phone);
  2274. Record lookup(const Phone); //  redeclares Record lookup(Phone)
  2275.  
  2276. Record lookup(Phone*);
  2277. Record lookup(Phone* const);    //  redeclares Record looup(Phone*)
  2278.  
  2279. In these declarations, the second declaration declares the same function as the first.
  2280.  
  2281. On the other hand, we can overload based on whether the parameter is a reference (or pointer) to the const or nonconst version of a given type; such consts are low-level:
  2282. //  functions taking const and nonconst references or pointers have different parameters
  2283. //  declarations for four independent, overloaded functions
  2284. Record lookup(Account&);    //  function that takes a reference to Account
  2285. Record lookup(const Account&);  //  new function that takes a const reference
  2286. Record lookup(Account*);    //  new function, takes a pointer to account
  2287. Record lookup(const Account*);  //  new function, takes a pointer to a const
  2288.  
  2289. In these cases, the compiler can use the constness of the argument to distinguish which function to call. Because there is no conversion from const, we can pass a const object (or a pointer to const) only to the version with a const
  2290. parameter. Because there is a conversion to const, we can call either function on a nonconst object or a pointer to nonconst. However, as we'll see in 6.6.1, the compiler will prefer the nonconst versionw hen we pass a nonconst object or pointer
  2291. to nonconst.
  2292.  
  2293. #const_cast and Overloaded
  2294. In 4.11.3 we noted that const_casts are most useful in the context of overloaded functions. As one example, recall our shorterString function from 6.3.2:
  2295. //  return a reference to the short of two strings
  2296. const string &shorterString(const string &s1, const string &s2)
  2297. {
  2298.     return s1.size(0 < s2,size() ? s1 : s2;
  2299. }
  2300.  
  2301. This function takes and returns a references to const string. We can call the function on a pair of nonconst string arguments, but we'll get a reference to a const string as the result. We might want to have a version of shorterString
  2302. that, when given nonconst arguments, would yield a plain reference. We can write this version fo our function using a const_cast:
  2303. string &shorterString(string &s1, string s2)
  2304. {
  2305.     auto &r = shorterString(const_cast<const string&>(s1), const_cast<const_string&>(s2));
  2306.     return const_cast<string&>(r);
  2307. }
  2308.  
  2309. This version calls the const version of shorterString by casting its arguments to const. That function returns a reference to a const string, which we know is bound to one of our original, nonconst arguments. Therefore, we know it is safe
  2310. to cast that string back to a plain string& in the return.
  2311.  
  2312. #Calling an Overloaded Function
  2313. Once we have defind a set of overloaded functions, we need to be able to call them with appropriate arguments. <Function matching> (also known as <overload resolution>) is the process by which a particular function call is associated with a
  2314. specific function from a set of overloaded functions. The copiler determines which function to call by comparing the argument in the call with the parameters offered by each function in the overload set.
  2315.  
  2316. For now, what's important to realize is that for any given call to be an overloaded function, there are three possible outcomes:
  2317.     -The compiler finds exactly one function that is a <best match> for the actual arguments and generates code to call that function.
  2318.     -There is no function with parameters that match the arguments in the call, in which case the comiler issues an error message that there was <no match>.
  2319.     -There is more than one function that matches and none of the matches is clearly best. This case is also an error; it is an <ambiguous call>.
  2320.  
  2321. #6.4.1 Overloading and Scope
  2322. string read();
  2323. void print(const string&);
  2324. void print(double); //  overloads the print function
  2325. void fooBar(int ival)
  2326. {
  2327.     bool read = false;  //  new scope: hides the outer declaration of read
  2328.     string s = read(0;  //  error: read is a bool variable, not a function
  2329.     //  bad practice: usually it's a bad idea to dclare functions at local scope
  2330.     void print(int);    //  new scope: hides previous instances of print
  2331.     print("Value: ");   //  error: print(const string &) is hidden
  2332.     print(ival;         //  ok: print(int) is visible
  2333.     print(3.14);        //  ok: calls print(int); print(double is hidden)
  2334. }
  2335.  
  2336. When we call print, the compiler first looks for a declaration of that name. It finds the local declaration for print that takes an int. Once a name is found, the compiler ignores uses of that name in any outer scope. Instead, the compiler
  2337. assumes that the declaration it found is the one for the name we are using. What remains is to see if the use of the name is valid.
  2338.  
  2339. The first call passes a string literal, but the only declaration for print that is in scope has a prameter that is an int. A string literal cannot be converted to an int, so this call is an error. The print(const string&) function, which would have
  2340. matched this call, is hidden and is not considered.
  2341.  
  2342. When we call print passing a double, the process is repeated. The compiler finds the local definition of print(int). The double argument can be converted to an int, so the call is legal.
  2343.  
  2344. Had we declared print(int) in the same scope as the other print functions, then it would be another overloaded version of print. In that case, these calls would be resolved differently, beacuse the compiler will see all three functions:
  2345. void print(const string &);
  2346. void brint(double); //  overloads the print function
  2347. void print(int);    //  another overloaded instance
  2348. void fooBar2(int ival)
  2349. {
  2350.     print("Value: ");   //  calls print(const strin g&)
  2351.     print(ival);        //  call print(int)
  2352.     print(3.14);        //  calls print(double)
  2353. }
  2354.  
  2355. #6.5.1 Default Arguments
  2356. Some functions have parameters that are given a particular value in most, but not all, calls. In such cases, we can declare that common value as a <default argument> for the function. Functions with default arguments can be called with or
  2357. without that argument
  2358.  
  2359. For example, we might use a string to represent the contents of a window. By default, we might want the window to have a particular height, width, and background character. However, we might also want to allow users to pass values other than the
  2360. defaults. To accommodate both default and specified values we woudl declare our function to define the window as follows:
  2361. typedef string::size_type sz:   //  typedef see 2.5.1
  2362. string screen(sz) ht = 24, sz wid = 80, char backgrnd = ' ');
  2363.  
  2364. Here we've provideda  default for each parmater. A default argument is specified as an initializer for a parmater in the parameter list. We may define defaults for one or more parameters. However, if a parameter has a default argument, all the
  2365. parameters that follow it must also have default arguments.
  2366.  
  2367. #Default Argument Initializers
  2368. Local variables may not be used as a default argument. Excepting that restriction, a default argument can be an expression that has a type that is convertible to the type of the parameter:
  2369. //  the declarations of wd, def, and ht must appear outside a function
  2370. sz wd = 80;
  2371. char def = ' ';
  2372. sz ht();
  2373. string screen9sz = ht(), sz = wd, char = def);
  2374. string window = screen();   //  calls screen(ht(),80,' ')
  2375.  
  2376. Names used as default arguments are resolved in the scope of the function declaration. The value that those names represent is evaluated at the time of the call:
  2377. void f2()
  2378. {
  2379.     def = '*';  //  changes the value of a default argument
  2380.     sz wd = 100;    //  hides the outer definition of wd but does not change the default
  2381.     window = screen();  //  calls screen(ht(), 80, '*')
  2382. }
  2383.  
  2384. #inline Functions Avoid Function Call Overhead
  2385. A function specified as <inline> (usually) is expanded "in line" at each call. If shorterString were defined as inline, then this call
  2386.     cout << shorterString(s1, s2) << endl;
  2387. (probably) would be expanded during compilation into something like
  2388.     cout << (s1.size() < s2,size() ? s1 : s2) << endl;
  2389. The run-time overhead of making shorterString a function is thus removed.
  2390.  
  2391. //  inline version: find the shorter of two strings
  2392. inline const string & shorterString(const string &s1, const string &s2,)
  2393. {
  2394.     return s1.size() <= s2.size() ? s1 : s2;
  2395. }
  2396.  
  2397. #constexpr Functions
  2398. A <constexpr function> is a function that can be used in a constant expression. A constexpr function is defined like any other function but must meet certain retrictions: The return and the type of each parameter must be a literal type,
  2399. and the function body must contain exactly one return statement:
  2400. constexpr int new_sz() { return 42; }
  2401. constexpr int foo = new_sze();  //  ok:: foo is a constant expression
  2402.  
  2403. A constexpr function is permitted to return a value that is not a constant:
  2404. //  scale(arg) is a constant expression if arg is a constant expression
  2405. constexpr size_t scale(size_t cnt) { return new_size() * cnt; }
  2406.  
  2407. The scale function will return a constant expression if its argument is a constant expression but not otherwise:
  2408. int arr[scale(2)];  //  ok: scale(2) is a constant expression
  2409. int i = 2;  //  i is not a constant expression
  2410. int a2[scale(i)];   //  error: scale(i) is not a constant expression
  2411.  
  2412. #6.5.3 Aids for Debugging
  2413. C++ programmers sometimes use a technique similar to header guards to conditionally execute debugging code. The idea is that the program will contain debugging code that is executed only while the program is being developed. When the application
  2414. is completed and ready to ship, the debugging code is turned off. This approach uses two preprocessor facilites: assert and NDEBUG.
  2415.  
  2416. #The assert Preprocessor Macro
  2417. <assert> is a <preprocessor macro>. A preprocessor macro is a preprocessor variable that acts somewhat like an inline function. The assert macro takes a single epxression, which is uses as a condition:
  2418.     assert(expr);
  2419. evalutes expr if the expression is false (i.e., zero), then assert writes a message and terminates the program. If the expression is true (i.e., nonzero), then assert does nothing.
  2420.  
  2421. The assert macro is defined in the cassert header. As we've seen, preprocessor names are managed by the preprocessor not the compiler. As a result, we use preprocessor names directly and do not provide a using declaration for them. That is,
  2422. we refer to assert, not std::assert, and provide no using declaration for assert.
  2423.  
  2424. The assert macro is often used to check for condition that "cannot happen." For example, a program that does some manipulation of input text might know that all words it is given are always longer than a threshold. That program might contain a
  2425. statement such as
  2426.     assert(word.size() > threshold);
  2427.    
  2428. #The NDEBUG Preprocessor Variable
  2429. The behavior of assert depends on the status of a preprocessor variable named NDEBUG. If NDEBUG is defined, assert does nothing. By default, NDEBUG is not defined, so, by default, assert performs a run-time check.
  2430.  
  2431. We can "turn off" debugging by providing a #define to define NDEBUG.
  2432.  
  2433. In addition to using assert, we can write our own conditional debugging code using NDEBUG. If NDEBUG is not defined, the code between the #ifndef and the #endif is exeucted. if NDEBUG is defined, that code is ignored:
  2434. void print(const int ai[], size_t size)
  2435. {
  2436.     #ifndef NDEBUG
  2437.     //  _ _func_ _ is a local static defined by the compiler that holds the function's name
  2438.     cerr << _ _func _ _ << ": array size is " << size << endl;
  2439.     #endif
  2440.     // ..
  2441. }
  2442.  
  2443. Here we use a variable named _ _func_ _ to print the name of the function we are debugging. The compiler defines _ _func_ _ in every fucntion. It is a local static array of const char that holds the name of the function.
  2444.  
  2445. In addition to _ _func_ _, which the C++ compiler defines, the preprocessor defines four other names that can be useful in debugging:
  2446.     _ _FILE_ _ string literal containing the name of the file
  2447.     _ _LINE_ _ integer literal containing the current line number
  2448.     _ _TIME_ _ string literal containing the time the file was compiled
  2449.     _ _DATE_ _ string literal containing the date the file was compiled.
  2450. We might use these constants to report additional information in error messages:
  2451. if (word.size() < threshold)
  2452.     cerr << "Error: "<< _ _FILE_ _
  2453.          << " : in function " << _ _func_ _
  2454.          << " at line " << _ _LINE_ _ << endl
  2455.          << "           Compiled on " << _ _DATE_ _
  2456.          << " at " << _ _TIME_ _ << endl
  2457.          << "           Word read was \"" << word
  2458.          << "\": Length too short" << endl;
  2459.  
  2460. If we give this program a string that is shorter than the threshold, then the following message will be generated:
  2461.     Error: wdebug.cc : in function main at line 27
  2462.         Compiled on Jul 11 2012 at 20:50:03
  2463.         Word read was "foo": Length too short
  2464.        
  2465. #6.6.1 Argument Type Conversions
  2466. In order to determine the best match, the compiler ranks the conversions that could be used to convert each argument to the type of its corresponding parameter. Conversions are ranked as follows:
  2467.     1. An exact match. An exact match happens when:
  2468.         The argument and paramter types are identical.
  2469.         The argument is converted from an array or function type to the corresponding pointer type.
  2470.         A top-level const is added to or discarded from the argument.
  2471.     2. Match through a const conversion. (4.11.2, p162)
  2472.     3. Match through a promotion. (4.11.1, p160)
  2473.     4. Match through an arithmetic ($4.11.1, p159) or pointer conversion (4.11.2, p161)
  2474.     5. Match through a class-type conversion. (14.9, p579)
  2475.    
  2476. #6.7 Pointers to Functions
  2477. A function pointer is just that-a pointer that denotes a function rather than an object. Like any other pointer, a function pointer points to a particular type. A function's type is determined by its return type and the type of its parameters. The
  2478. function's name is not part of its type. For Example:
  2479. //  compares lengths of two strings
  2480. bool lengthCompare(const string &, const string &);
  2481. has type bool(const string&, const string&). To declare a pointer that can point at this function, we declare a pointer in place of the function name
  2482. //  pf points to a function returning bool that takes two const string references
  2483. bool (*pf)(const string &, const string &); //  uninitialized
  2484.  
  2485. Starting from the name we are declaring, we see that pf is preceded by a *, so pf is a pointer. To the right is a paramter list, which means that pf points to a function. Looking left, we find that the type the function returns is bool. Thus, pf
  2486. points to a function that has two const string& paramters and returns bool.
  2487.  
  2488. #Using Function Pointers
  2489. When we use the name of a function as a value, the function is automatically converted to a pointer. For example, we can assign the address of lengthCompare to pf as follows:
  2490. pf = lengthCompare; //  pf now points to the function named lengthCompare
  2491. pf = &lengthCompare;    //  equivalent assignment: address-of operator is optional
  2492.  
  2493. Moreover, we can use a pointer to a function to call the function to which the pointer points. We can do so directly-there is no need to dereference the pointer:
  2494. bool bq = pf("hello", "goodbye");   //  calls lengthCompare
  2495. bool b2 = (*pf)("hello", "goodbye");    //  equivalent call
  2496. bool b3 = lengthCompare("hello", "goodbye");    //  equivalent call
  2497.  
  2498. There is no conversion between pointers to one function type and pointers to another function type. However, as usual, we can assign nullptr or a zero-valued integer constant expression to a function pointer to indicate that the pointer does not
  2499. point to any function:
  2500. string::size_type sumLength(const string&, const string&);
  2501. bool cstrongCompare(const char*, const char*);
  2502. pf = 0; //  ok: pf points to no function
  2503. pf = sumLength; //  error: return type differs
  2504. pf = cstringCompare;    //  error: parameter types differ
  2505. pf = lengthCompare; //  ok: function and pointer types match exactly
  2506.  
  2507. #Pointers to Overloaded Functions
  2508. As usual, when we u se an overloaded function, the context must make it clear which version is being used. When we declare a pointer to an overlaoded function
  2509. void ff(int*);
  2510. void ff(unsigned int);
  2511. void (*pf1)(unsigned int) = ff; //  pf1 points to ff(unsigned)
  2512. the compiler uses the type of the pointer to determine which overloaded function to use. The type of the pointer must match one of the overloaded functions exactly:
  2513. void (*pf2)(int) = ff;  //  error: no ff with a matching paramter list
  2514. double (*pf3)(int*) = ff;   //  error: return type of ff and pf3 don't match
  2515.  
  2516. #Function Pointer Parameters
  2517. Just as with arrays, we cannot define parmaters of function type but we can have a paramter that is a pointer to a function. As with arrays, we can write a paramter that looks like a function type, but it will be treated as a pointer:
  2518. //  third paramter is a function type and is autmatically treated as a pointer to function
  2519. void useBigger(const string &s1, const string &s2, bool pf(const string &, const string&));
  2520. //  equivalent declaration: explicitly define the parameter as a pointer to function
  2521. void useBigger(const string &s1, const string &s2, bool (*pf)(const string &, const string &));
  2522.  
  2523. When we pass a function as an argument, we can do so directly. It will be automatically converted to a pointer:
  2524. //  automatically converst thef unction lengthCompare to a pointer to function
  2525. useBigger(s1, s2, lengthCompare);
  2526.  
  2527. As we've just seen in the declaration of useBigger, writing function pointer types quickly gets tedius. Type aliases, along with decltype, let us simplify code that uses function pointers:
  2528. typedef bool Func(const string&, const string&);
  2529. typedef decltype(lengthCompare) Func2;  //  equivalent type
  2530. //  FuncP and FuncP2 have pointer to function type
  2531. typedef bool(*FuncP)(const string&, const string&);
  2532. typedef decltype(LengthCompare) *FuncP2;    //  equivalent type
  2533. Here we used typedef to define our types. Both Func and Func2 are function types, whereas FuncP and FuncP2 are pointer types. It is important to note that decltype returns the function type; the automatic conversion to pointer is not done. Because
  2534. decltype returns a function type, if we want a pointer we must add the * ourselves. We can redeclare useBigger using any of these types:
  2535. //  equivalent declarations of useBigger using type aliases
  2536. void useBigger(const string&, const string*, Func);
  2537. void useBigger(const string&, const string*, FuncP2);
  2538.  
  2539. Both declarations declare the same function. In the first case, the compiler will automatically convert the function type represented by Func to a pointer.
  2540.  
  2541. #returning a pointer to function
  2542. As with arrays, we can't return a function type but can return a pointer to a function type. Similarly, we must write the return type as a pointer type; the compiler will not automatically treat a function that has return type as the fcorresponding
  2543. pointer type. Also with array returns, by far the easiest way to declare a funciton that returns a pointer to function is by using a type alias:
  2544. using F = int(int*, int);   //  F is a function type, not a pointer
  2545. using PF = int(*)(int*, int);   //  PF is a pointer type
  2546.  
  2547. Here we used type alias declarations to define F as a function type and PF as a pointer to function type. The thing to keep in mind is that, unlike what happens to parameters that have function type, the return type is not automatically converted to a
  2548. pointer type. We must explicitly specify that the return type is a pointer type:
  2549. PF f1(int); //  ok: PF is a pointer to function; f1 returns a pinter to function
  2550. F f1(int);  //  error: F is a function type; f1 can't return a function
  2551. F *f1(int); //  ok: explicitly specify that the return type is a pointer to a function
  2552.  
  2553. Of course, we can also declare f1 directly, which we'd do as
  2554. int (*f1(int))(int*, int);
  2555. Reading this declaration from the inside out, we see that f1 has a paramter list, so f1 is a function. f1 is preceded by a * so f1 returns a pointer. The type of that pointer itself has a paramter list, so the pointer points to a function. That
  2556. function returns an int.
  2557.  
  2558. For completeness, it's worth noting that we can simplify declarations of functions that return pointers to function by using a trailing return:
  2559. auto f1(int) -> int (*)(int *, int);
  2560.  
  2561. #Using auto or decltype for Function Pointer Types
  2562. If we know which function(s) we want to return, we can use decltype to simplify writing a function pointer return type. For example, assume we have two functions, both of which return a string:;size_type and have two const string& paramters. We can write
  2563. a third function that takes a string paramter and returns a pointer to one of these two functions as follows:
  2564. string::size_type sumLength(const string&, const string&);
  2565. string::size_type largerLength(const string&, const string&);
  2566. //  depending on the value of its string parmater, getFcn returns a pointer to sumLength or to largerLength
  2567. deecltype(sumLength) *getFcn(const string &);
  2568.  
  2569. The only tricky part in declaring getFcn is to remember that when we apply decltype to a function, it returns a function type, not a pointer to function type. We must add a * to indice that we are returning a pointer, not a function.
Advertisement
Add Comment
Please, Sign In to add comment