Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Chapter 1*/
- While Statement: Repeatedly executes a section of code so long as a given condition is true.
- Condition: Is an expression that yields a result that is either true or false. It goes inside the ()
- For statement:
- for (int val = 1; val <= 10; ++val)
- Each for statement has two parts: a header and a body.
- The header controls how often the body is executed.
- an int statement (val = 1)
- a condition (val <= 10)
- and an expression (++val)
- The variable val exists only inside the for; it is not possible to use val after this loop terminates
- The init-statement is executed only once, on entry to the for
- 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.
- 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)
- After executing the expression, the for retests the condition.
- /*Chapter 2*/
- #Table Types:
- Type: Meaning: Minimum Size
- bool boolean NA
- char character 8 bits
- wchar_t wide character 16 bits
- char16_t Unicode character 16 bits
- char32_t Unicode character 32 bits
- short short integer 16 bits
- int integer 16 bits
- long long integer 32 bits
- long long long integer 64 bits
- float single-precision floating-point 6 significant digits
- double double-precision floating-point 10 significant digits
- long double extended-precision floating-point 10 significant digits
- Group Type names* Notes on size / precision
- Character types
- char Exactly one byte in size. At least 8 bits.
- char16_t Not smaller than char. At least 16 bits.
- char32_t Not smaller than char16_t. At least 32 bits.
- wchar_t Can represent the largest supported character set.
- Integer types (signed)
- signed char Same size as char. At least 8 bits.
- signed short int Not smaller than char. At least 16 bits.
- signed int Not smaller than short. At least 16 bits.
- signed long int Not smaller than int. At least 32 bits.
- signed long long int Not smaller than long. At least 64 bits.
- Integer types (unsigned)
- unsigned char (same size as their signed counterparts)
- unsigned short int
- unsigned int
- unsigned long int
- unsigned long long int
- Floating-point types
- float
- double Precision not less than float
- long double Precision not less than double
- Boolean type
- bool
- Void type
- void no storage
- Null pointer
- decltype(nullptr)
- 0 = False
- 1 = True
- 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.
- 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
- 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.
- 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.
- Ex. 20 // decimal
- 024 // octal
- 0x14 // hexadecimal
- #Table 2.2
- //Character and Character String Literals
- Prefix Meaning Type
- u Unicode 16 character char16_t
- U Unicode 32 character char32_t
- L Wide character wchar_t
- u8 utf-8 (string literals) char
- //Integer Literals
- Suffix Minimum Type
- u or U Unsigned
- l or L Long
- ll or LL Long long
- //Floating-Point literals
- Suffix Type
- f or F Float
- l or L Long Double
- 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:
- 3.14159 3.14159E0 0. 0e0 .001
- #Nonprintable Characters
- newline \n horizontal tab \t alert (bell) \a
- verticle tab \v backspace \b double quote \"
- backslash \\ question mark \? single quote \"
- carriage return \r formfeed \f
- int units_sold = 0;
- int units_sold = {0};
- int units_sold{0};
- int units_sold(0);
- 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>.
- 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.
- 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
- Declaration: makesa name known to the program.
- Definition: creates the associated entity.
- To obtain a declaration that is not also a definition, we add the extern keyword and may not provide an explicit initializer:
- extern int i; // declares but does not define i
- int j // declares and defines j
- #Table 2.3 C++ Keywords
- alignas continue friend register true
- alignof decltype goto reinterpret_cast try
- asm default if return typedef
- auto delete inline short typeid
- bool do int signed typename
- break double long sizeof union
- case dynamic_cast mutable static unsigned
- catch else namespace static_assert using
- char enum new static_cast virtual
- char16_t explicit noexcept struct void
- char32_t export nullptr switch volatile
- class extern operator template wchar_t
- const false private this while
- constexpr float protected thread_local
- const_cast for public throw
- #Table 2.4 C++ Alternative Operator Names
- and bitand compl not_eq or_eq xor_eq
- and_eq bitor not or xor
- Reference: Defines an alternate name for an object. A reference "refers to" another type. (&variable)
- Pointer: Compound type that "poitns to" another type (*variable)
- (A pointer holds the address of another object. We get the address of an object by using the address-of operator (the <& operator>))
- int *p = &number (pointer point is of type int that holds the address of number)
- (When a pointer points to an object, we can use the dereference operator ( the <* operator>) to access that object)
- cout << *p << endl;
- Type Alias: Name that is a synonym for another type. (typedef and using)
- struct (variable) { type variable; type variable2; type variable3; ..};
- #ifndef SALES_DATA_H
- #define SALES_DATA_H
- #include <string>
- struct Sales_data
- {
- string bookNo;
- unsigned units_sold = 0;
- double revenue = 0.0;
- };
- #endif
- /*Chapter 3*/
- using std::cin; using std::cout; using std::endl; using std::string;
- 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
- using declaration. As a result, the program that didn't intend to use the specified library name might encounter unexpected name conflits.
- #Table 3.1 Ways to Initialize a string
- string s1 // Default initialization; s1 is the empty string.
- string s2(s1) // s2 is a copy of s1.
- string s2 = s1 // Equivalent to s2(s1), s2 is a copy of s1.
- string s3("value") // s3 is a copy of the string literal, not including the null.
- string s3 = "Value" // Equivalent to s3("Value"), s3 is a copy of the string literal.
- string s4(n, 'c') // Initialize s4 with n copies of the character 'c'.
- #Table 3.2 string Operations
- os << s // Writes s onto output strom os. Returns os.
- is >> s // Reads whitespace-separated string from is inot s. Returns is.
- getline(is, s) // Reads a line of input from is inot s. Returns is.
- s.empty() // Returns true if s is empty; otherwise returns false
- s.size() // Returns the number of characters in s.
- s[n] // Returns a reference to the character at position n in s; positions start at 0.
- s1 + s2 // Returns a string that is the concatentation of s1 and s2.
- s1 = s2 // Replaces characters in s1 with a copy of s2.
- s1 == s2 // The strings s1 and s2 are equal if they contain the same characters.
- s1 != s2 // Equality is case-senitive.
- <,<=, >, >= // Comparisions are case-sensitive and use dicitionary ordering.
- #Reading and Writing strings
- 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:
- int main()
- {
- string s; // empty string
- cin >> s; // read a whitespace-separated string inot s
- cout << s < endl; // writes s to the output
- return 0;
- }
- // using getline to return a whole input, not one word at a time
- int main()
- {
- string line;
- // read input a line at a time until end-of-file
- while (getline(cin, line))
- cout << line << endl;
- return 0;
- }
- 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.
- 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:
- size_type sizet = line.size()
- auto len = line.size(); // len has type string::size_type
- 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
- 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:
- 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.
- 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.
- string str= "Hello"; // less than phrase, rule 1
- string phrase = "Hello World";
- string slang = "Hiya"; // greater than both, rule 2
- When we mix strings and string or character literals, at least one operand to each + operator must be of string type:
- string s4 = s1 + ", "; // ok: adding a string and a literal
- string s5 = "hello" + ", "; // error: no string operand
- string s6 = s1 + ", " + "world"; // ok: each + has a string operand
- string s7 = "hello" + ", " + s2; // error: can't add string literals
- 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
- expressions. This initialization groups as
- string s6 = (s1 + ", ") + "world";
- ****Warning****
- 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.
- #Table 3.3 cctype Functions
- isalnum(c) // true if c is a letter of digit.
- isalpha(c) // true if c is a letter.
- iscntrl(c) // true if c is a control character.
- isdigit(c) // true if c is a digit.
- isgraph(c) // true if c is not a space but is printable.
- islower(c) // true if c is a lowercase letter.
- isprint(c) // true if c is a printable character (i.e., a space or a character that has a visible representation).
- 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).
- isspace(c) // true if c is a whitespace (i.e., a space, tab, vertical tab, return, newline, or formfeed).
- isupper(c) // true if c is an uppercase letter.
- isxdigit(c) // true if c is a hexadecimal digit
- tolower(c) // If c is an uppercase letter, returns its lowercase equivalent; otherwise returns c unchanged.
- toupper(c) // If c is a lowercase letter, turns its uppercase equivalent; otherwise returns c unchanged.
- //Range for: do something to every character in a string. Statement iterates through the elements in a given sequence.
- for (declaration : expression)
- {
- statement
- }
- string str("some string");
- // print the character in str one character to a line
- for (auto c : str) // for every character in str
- {
- cout << c << endl; // print the current character followed by a new line
- }
- string s("Hello World!!!");
- // punct_cnt has the same type that s.size returns
- decltype(s.size()) punct_cnt = 0;
- // count the number of punctuation characters in s
- for (auto c : s) // for every char in s
- {
- if (ispunct(c)) // if the character is a punctuation
- {
- ++punct_cnt; // increment the punctuation counter
- }
- }
- cout << punct_cnt << " punctuation characters in " << s << endl;
- string s("Hello World!!!");
- // convert s to uppercase
- for ( auto &c : s) // for every char in s (note: c is a reference)
- {
- c = toupper(c); // c is a reference, so the assignment changes the char in s
- }
- cout << s << endl;
- if (!s.empty()) // make sure there's a character to print
- {
- cout << s[0] << endl; // print the first character in s
- }
- string s("some string");
- if (!s.emtpy()) // make sure there's a character in s[0]
- {
- s[0] = toupper(s[0]); // assign a new value to the first character in s
- // Prints "Some string"
- }
- string s("some string");
- // process characters in s until we run out of characters or we hit a whitespace
- for (decltype(s.size()) index = 0; index != s.size() && !isspace(s[index]); ++index)
- {
- s[index] = toupper(s[index]); // capitalize the current character
- }
- cout << s << endl;
- // Prints "SOME string"
- ****Caution: Subscripts are Unchecked****
- 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
- 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().
- const string hexdigits = "0123456789ABCDEF"; // possible hex digits
- cout << "Enter a series of numbers between 0 and 15 seperated by spaces, Hit ENTER when finished:" << endl;
- string result; // will hold the resulting hexify'd string
- string::size_type n; // hold numbers from the input, string::size_type is a very large numerical type
- while (cin >> n)
- {
- if (n < hexdigits.size()) // ignore invalid input
- {
- result += hexdigits[n]; // fetch the indicated hex digit
- }
- cout << "Your hex number is " << result << endl;
- }
- #Vector
- Vector: A collection of objects, all of which have the same type. Often referred to as a "container" because it "contains" other objects.
- #Table 3.4 Ways to Initialize a vector
- vector<T> v1 // vector that holds objects of type t. Default initialization. v1 is empty
- vector<T> v2(v1) // v2 has a copy of each element in v1.
- vector<T> v2 = v1 // Equivalent to v2(v1), v2 is a copy of the elements in v1.
- vector<T> v3(n, val) // v3 has n elements with value val.
- vector<T> v4(n) // v4 has n copies of a value-initialized object.
- vector<T> v5{a,b,c...} // v5 has as many elements as there are initializers; elements are initialized by corresponding initializers.
- vector<T> v5 = {a,b,c...} // Equivalent to v5{a,v,c...}.
- vector<int> ivec; // initially empty
- // give ivec some values
- vector<int> ivec2(ivec); // copy elements of ivec inot ivec2
- vector<int> ivec3 = ivec; // copy elements of ivec inot ivec3
- vector<string> svec(ivec2); // error: svec holds strings, not ints
- #List Initializing a vector
- vector<string> articles = {"a", "an", "the"}; // List initialization uses curl braces ({})
- #List Initializer or Element Count?
- 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
- 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
- or parentheses:
- vector<int> v1(10); // v1 has ten elements with value 0
- vector<int> v2{10}; // v2 has one element with value 10
- vector<int> v3(10, 1); // v3 has ten elements with value 1
- vector<int> v4{10, 1}; // v4 has two elements with values 10 and 1
- We cannot use a range for if the body of the loop adds elements to the vector.
- #Table 3.5 vector Operations
- v.empty() // Returns true if v is empty; otherwise returns false.
- v.size() // Returns the number of elements in v.
- v.push_back(t) // Adds an element with value t to end of v.
- v[n] // Returns a reference to the element at position n in v.
- v1 = v2 // Replaces the elements in v1 with a copy of the elements in v2.
- v1 = {a,b,c...} // Replaces the elements in v1 with a copy of the elements in the comma-separated list.
- 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
- v1 != v2 // v1 cannot be equal to v2
- <, <=, >, >= // Have their normal meanings using dictionary ordering.
- 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,
- then the relationship between the vectors is determined by the relationship between the first elements that differ.
- vector<int> v1{1,2,3,4,5,6,7,8,9}
- vector<int> v2{2,4,6,8,10}
- vector<int> v2{1,2,3,4}
- v1 < v2 | v1 > v3 | v2 > v3
- // subscript example
- // count the number of grades by clusters of 10: 0--9, 10--19, . .. 90-99, 100
- vector<unsigned> scores(11, 0); // 11 buckets, all initially 0
- unsigned grade;
- while (cin >> grade) // read the grades
- {
- if (grade <= 100) // handle only valid grades
- {
- ++scores[grade/10]; // increment the counter for the current cluster
- }
- }
- #Iterator
- 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.
- #Table 3.6 Standard Container Iterator Operations
- *iter // Returns a reference to the element donated by the iterator iter.
- iter->mem // Dereferences iter and fetches the member named mem from the underlying element. Equivalent to (*iter).mem
- ++iter // Increments iter to refer to the next element in the container.
- --iter // Decrements iter to refer to he previous element in the container.
- 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
- iter1 != iter2
- if (s.begin() != s.end()) // make sure s is not empty
- {
- auto it = s.begin(); // it denotes the first character in s
- *it = toupper(*it); // make that character uppercase
- }
- // iterator example
- for (auto it = s.begin (); it != s.end() && !isspace(*t); ++it)
- {
- *it = toupper(*it); // capitalize the current character
- }
- vectir<int>::iterator it; // it can read and write vector<int> elements
- string::iterator it2; // it2 can read and write characters in a string
- vector<int>::const_iterator it3; // it3 can read by not write elements
- string::const_iterator it4; // it4 can read by not write characters
- vector<int> v;
- const vector<int> cv;
- auto it1 = v.begin(); // it1 has the type vector<int>::iterator
- auto it2 = cv.begin(); // it2 has type vector<int>::const_iterator
- 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
- introduced two new functions named cbegin and cend:
- auto it3 = v.cbegin(); // it3 has type vector<int>::const_iterator
- (*it).empty // dereferences it and calls the member empty on the resulting object
- *it.empty() // error: attempts to fetch the member named empty from it but it is an iterator and has no member named empty
- #Table 3.7 Operations supported by vector and string ierators
- 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,
- iter - n // the same container.
- iter1 += n // Compound-assignment for iterator addition and u bsctrion. Assigns iter1 the value of adding n to, or subtracting n from, iter1.
- iter1 -= n
- 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.
- >, >=, <, <= // 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
- // past the end of, the same comtainer.
- // text must be sorted. beg and end will denote the range we're searching
- auto beg = text.begin(), end = text.end();
- auto mid = text.begin() + (end - beg) / 2; // original midpoint
- // while there are still elements to look at and we haven't found sought
- while (mid != end && *mid != sought)
- {
- if (sought < *mid) // is the element we want in the first half?
- {
- end = mid; // if so, adjust the range to ignore the second half
- }
- else // the element we want is in the second half
- {
- beg = mid +1; // start looking with the element just after mid
- mid = beg + (end - beg) / 2; // new midpoint
- }
- }
- #Array
- 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
- for specialized applicaitons.
- const unsigned sz = 3;
- int ia1[sz] = {0,1,2}; // array of three ints with values 0, 1, 2
- int a2[] = {0, 1, 2}; // any array of dimension 3
- int a3[6] = {0, 1, 2}; // equivalent to a3[] = {0, 1, 2, 0, 0, 0}
- string a4[3] = ("hi", "bye") // same as a4[] = {"hi", "bye", ""}
- int a5[2] = {0, 1, 2}; // error: too many initializers
- #No Copy Or Assignment (on arrays)
- We cannot initialize an array as a copy of another array, nor is it legal to assign one array to another;
- int a[] = {0, 1, 2}; // array of three ints
- int a2[] = a; // error: cannot initialize one array with another
- a2 = a; // error: cannot assign one array to another
- #Understanding Complicated Array Declarations
- #Tip: It can be easier to understand array declarations by starting with the array's name and reading them from the inside out.
- 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
- straightforward, defining a pointer or reference to an array is a it more complicated:
- int *ptrs[10]; // ptrs is an array of ten pointers to int
- int &refs[10] = /* ? */ // error: no arrays of references
- int (*Parray)[10] = &arr // Parray points to an array of ten ints
- int (&arrRef)[10] = arr; // arrRef refers to an array of ten ints
- 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.
- 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
- 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
- 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.
- int *(&array)[10] = ptrs; // array is a reference to an array of ten pointers
- 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
- reference to an array of ten pointers.
- #3.5.2 Accessing the Elements of an Array
- #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.
- # The size_t type is defined in the cstddef header, which is the C++ version of the stddef.h header from the C Library.
- // count the number of grades by clusters of 10: 0--9, 10-19, ... 90-99, 100
- unsigned scores[11] = {}; // 11 buckets, all value initialized to 0
- unsigned grade;
- while (cin >> grade)
- {
- if (grade <= 100)
- {
- ++scores[grade/10]; // increment the counter for the current cluster
- }
- }
- for (auto i : scores) // for each counter in scores
- {
- cout << i << " "; // print the value of that counter
- cout << << endl;
- }
- 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:
- int ia[] = {0,1,2,3,4,5,6,7,8,9}; // ia is an array of ten ints
- auto ia2(ia); // ia2 is an int* that points to the first element in ia
- ia2 = 42; // error: ia2 is a pointer, we can't assign an int to a pointer
- 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:
- auto ia2(&ia[0]); // now it's clear that ia2 h as type int*
- #Pointers Are Iterators
- 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
- operator to move from one element in an array to the next:
- int arr[] = {0,1,2,3,4,5,6,7,8,9}
- int *p = arr; // p points to the first element in arr
- ++p; // p points to arr[1]
- // traversing an array using pointers
- int *e = &arr[10]; // pointer just past the last element in arr
- for (int *b = arr; b != e; ++b)
- {
- cout << *b << endl; // print the elements in arr
- }
- #Pointer Arithmetic
- #Pointers that address array elements can use all the iterator operations listed in Table 3.6 and Table 3.7
- constexpr size_t sz = 5;
- int arr[sz] = {1,2,3,4,5};
- int *ip = arr; // equivalent to int *ip = &arr[0]
- int *ip2 = ip + 4; // ip2 points to arr[4], the last element in arry
- // ok: arr is converted to a pointer to its first element: p points one past the last end of arr
- int *p = arr + sz; // use caution -- do not dereference
- int *p2 = arr + 10; // error: arr has only 5 elements; p2 is undefined value
- #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.
- int *p = &ia[2]; // p points to the element indexed by 2
- int j = p[1]; // p[1] is equivalent to *{p + 1)
- // p[1] is the same element as ia[3]
- int k = p[-2]; // p[-2] is the same element as ia[0] // k = 0
- #Warning: Unlike subscripts for vector and string, the index of the built-in subscript operator is not an unsigned type.
- #3.5.4 C-Style Character Strings
- 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
- 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.
- #These functions are defined in the cstring header
- #Table 3.8 C-Style Character String Functions
- strlen(p) // Returns the length of p, not counting the null.
- 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.
- strcat(p1,p2) // Appends p2 to p1. Returns p1.
- strcpy(p1, p2) // Copies p2 inot p1. Returns p1
- The pointer(s) passed to these routines must point to null-terminated array(s):
- char ca[] = {'C', '+', '+'}; // not null terminated
- cout << strlen(ca) << endl; // disaster: ca isn't null terminated
- #Comparing Strings
- #Standard C++ library strings
- string s1 = "A string example";
- string s2 = "A different string";
- if (s1 < s2) // false: s2 is less than s1
- #C-style strings
- const char ca1[] = "A string example";
- const char ca2[] = "A different string";
- if (ca1 < ca2) // undefined: compares two unrelated addresses
- // 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.
- if (strcmp(ca1, ca2) < 0) // same effect as string comparison s1 < s2
- // 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
- // C++ Strings: Concantenting two standard library strings inot one string called largeStr
- // initialize largeStr as a concatenation of s1, a space, and s2
- string largeStr = s1 + " " + s2;
- // C-Style strings: Concantenting two strings inot an array called largeStr
- // disastrous if we miscalculate the size of largeStr
- strcpy(largeStr, ca1); // copies ca1 inot largeStr
- strcat(largeStr, " "); // adds a space at the end of largeStr
- strcat(largeStr, cat2); // concatenates ca2 onot largeStr
- 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
- similar to this code are widely distributed. Programs with such code are error-prone and often lead to serious security leaks.
- #Mixing Library strings and C-Style Strings
- More generally, we can use a null-terminated character array anywhere that we can use a string literal:
- *We can use a null-terminated character array to initialize or assign a string.
- *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.
- 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:
- char *str = s; // error: can't initialize char* from a string
- const char *str = s.c_str(); // ok
- #Using an Array to Initialize a vector
- 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
- one pas tht elast element that we wish to copy:
- int int_arr[] = {0,1,2,3,4,5};
- // ivec has sixe elements; each is a copy of the corrsponding elements in int_arr
- vector<int> ivec(begin(int_arr), end(int_arr));
- The specified range can be a subset of the array:
- // copies three elements: int_arr[1], int_arr[2], int_arr[3]
- vector<int> subVec(int_arr + 1, int_arr + 4);
- 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].
- #3.6 Multidimensional Arrays
- #There are no multidimensional arrays in C++. They are actually arrays of arrays (of arrays of arrays, etc).
- We define an array whose elements are arrays by providing two dimensions: the dimension of the array itself and the dimension of its elements:
- int ia[3][4]; // array of size 3; each element is an array of ints of size 4
- // array of size 10; each element is a 20-element array whose elements are arrays of 30 ints
- int arr[10][20][30] = {0}; // initialize all elements to 0
- #Two-dimensional array: The first dimension is usually referred to as the row and the second is the column.
- int ia[3][4] = { // three elements, each element is an array of size 4
- {0,1,2,3}, // initializers the row indexed by 0
- {4.5.6.7}, // initializers the row indexed by 1
- {8,9,10,11} // initializers for the row index by 2
- };
- 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:
- // explicitly initialize only element 0 in each row
- int ia[3][4] = {{0},{4},{8}};
- // assigns the first element of arr to the last element in the last row of ia
- ia[2][3] = arr[0][0][0];
- int (&row)[4] = ia[1]; // binds row to the second four-element array in ia
- // Pair of nesteed for loops to process the elements in a multidimensional array
- constexpr size_t rowCnt = 3, colCnt = 4;
- int ia[rowCnt][colCnt]; // 12 uninitialized elements
- // for each row
- for (size_t i = 0; i != rowCnt; ++i)
- {
- for (size_t j = 0; j!= colCnt; ++j)
- {
- ia[i][j] = i * colCnt + j;
- }
- }
- // Does the same thing as above except in a range for
- for (const auto &row : ia) // for every element in the outer array
- {
- for (auto col : row) // for every element in the inner array
- {
- cout << col << endl;
- }
- }
- 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.
- // Note: To use a multidimensional array in a range for, the loop control variable for all but the inntermost array must be references.
- 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:
- // print the value of each element in ia, with each inner array on its own line
- for (auto p = ia; p != ia + 3; ++p) // p points to an array of four ints
- {
- 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
- {
- cout << *q << ' ';
- }
- cout << endl;
- }
- Of course, we can even more easily write this loop using the library begin and end functions:
- for (auto p = begin(ia); p != end(ia); ++p) // p points to the first in ia
- {
- for (auto q = begin(*p); q != end(*p); ++q) // q points to the first element in an inner array
- {
- cout << *q << ' '; // prints the int value to which q points
- }
- cout << endl;
- }
- #Type Aliases Simplify Pointers to Multidimensional Arrays
- A type alias can make it easier to read, and understand pointers to multidimensional arrays. For example:
- using int_array = int[4]; // new style type alias declaration
- typedef int int_array[4]; // equivalent typedef declaration
- // print the value of each element in ia, with each inner array on its own life
- for (int_array *p = ia; p != ia + 3; ++p)
- {
- for (int *q = *p; q != *p + 4; ++q)
- {
- cout << *q << ' ';
- }
- cout << endl;
- }
- /* Chapter 4 */
- #4.1.1 Basic Concepts
- 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
- ternary operator that takes three operands, and one operator, function call, that takes an unlimited number of operands.
- #Grouping Operators and Operands
- 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.
- #Operand Conversions
- Operands are often converted from one type to another.
- 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
- 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.
- #Lvalues and Rvalues
- Every expression in C++ is either an <rvalue> (pronounced "are-value") or an <lvalue> (pronounced "ell-value").
- 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
- 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).
- 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)
- 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.
- *Assignment requires a (nonconst) lvalue as its left-hand operand and yields its left-hand operand as an lvalue.
- *The address-of operator requires an lvalue operand and returns a pointer to its operand as an rvalue.
- *The built-in dereference and subscript oeperators and the iterator dereference and string and vector subscript operators all yield lvalues.
- *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.
- 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
- 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.
- #4.1.2 Precedence and Associativity
- 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
- 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.
- 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
- 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
- arithmetic operators are left associative, which means operators at the same precdence group left to right:
- *Because of precedence, the expression 3+4*5 is 23, not 35.
- *Because of associativity, the expression 20-15-3 is 2, not 8.
- As a more complicated example, a left-to-right evaluation of the following expression yields 20:
- 6 + 3 * 4 / 2 + 2
- Other than imaginable results including 9, 14, and 36. In C++, the result is 14 because this expression is equivalent to
- // parentheses in this expression match default precedence and associativity
- ((6 + ((3 * 4) / 2 )) + 2)
- #Parentheses Override Precedence and Associativity
- 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
- to force the result to be any of the four possible values:
- // parentheses result in alternative groupings
- cout << (6 + 3 ) * (4 / 2 + 2) << endl; // prints 36
- cout << ((6 + 3) * 4) / 2 + 2) << endl; // prints 20
- cout << 6 = 3 * 4 / ( 2 + 2) << endl; // prints 9
- #When Precedence and Associativity Matter
- 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:
- int ia[] = {0,2,4,6,8} // array of five elements of type int
- int last = *(ia+4); // initializes last to 8, the value of is[4]
- last = *ia +4; // last = 4, equivalent to ia[0] + 4
- 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.
- #4.1.3 Order Of Evaluation
- 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
- its operands are evaluated. As a result, the following output expression is undefined:
- int i = 0;
- cout << i << " " << ++i << endl; // undefined
- 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
- 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.
- #Order of Evaluation, Precedence, and Associativity
- Order of operand evaluation is independent of precedence and associativity. In an expression such as f() + g() * h() + j();
- *Precedence guarantees that the results of g() and h() are multiplied.
- *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().
- *There are no guarntees as to the order in which these functions are called.
- 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
- in error and has undefined behavior.
- #4.2 Arithmetic Operators
- 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
- 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
- levels are the same.
- #Table 4.1 Arithmetic Operators (Left Associative)
- Operator Function Use
- + unary plus + expr
- - unary minus - expr
- __________________________________________________
- * multiplication expr * expr
- / division expr / expr
- % remainder exper % expr
- __________________________________________________
- + addition expr + expr
- - subtraction expr - expr
- 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.
- int i = 1024;
- int k = -i; // i is -1024
- bool b = true;
- bool b2 = -b; // b2 is true!
- ****Caution: Overflow and Other Arithmetic Exceptions****
- 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
- happens when a value is computed that is outside the range of values that the type can represent.
- 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:
- short short_value = 32767; // max value if shorts are 16 bits
- short_value += 1; // this calculation overflows
- cout << "short_value: " << short_value << endl;
- 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
- behavior, what happens is unpredictable. On our systems the program completes and writes
- short_value: -32768
- 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.
- Division between integers returns an integer. If the quotient contains a fractional part, it is truncated toward zero:
- int ival1 = 21/6; // ival1 is 3; result is truncated; remainer is discarded
- int ival2 = 21/7; // ival2 is 3; no remainder; result is an integral value
- 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:
- int ival = 42
- double dval = 3.14;
- ival % 12; // ok: result is 6
- ival % dval; // error: floating-point operand
- 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
- 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
- m%n, and (-m)%n is equal to -(m%n). More concretely:
- 21 % 6; result is 3 21/6; result is 3
- 21 % 7; result is 0 21/7 result is 3
- -21 % -8 result is -5 -21/-8 result is 2
- 21 % -5 result is 1 21 / -5 result is -4
- #Table 4.2 Logical and Relational Operators
- Associativity Operator Function Use
- Right ! logical NOT !expr
- ________________________________________________________________
- Left < less than expr < expr
- Left <= less than or equal expr <= expr
- Left > greater than expr > expr
- Left >= greater than or equal expr >= expr
- _________________________________________________________________
- Left == equality expr == expr
- Left != inequality expr != expr
- _________________________________________________________________
- Left && logical AND expr && expr
- _________________________________________________________________
- Left || logical OR expr || expr
- // print the first element in vec if there is one
- if (!vec.empty())
- {
- cout << vec[0];
- }
- #The Relation Operators
- The relation operators (<, <=, >, >=) have their ordinary meanings and return bool values. These operators are left associative.
- Because the relational operators return bools, the result of chaining these operators together is likely to be surprising:
- // oops! this condition compares k to the bool result of i < j
- if (i < j < k) // true if k is greater than 1
- 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,
- we can rewrite the expression as follows:
- // ok: condition is true if i is smaller than j and j is smaller than k
- if (i < j && j < k) { /* ... */ }
- #4.4 Assignment Operators
- Under the new standard we can use a braced initializer list on the right-hand side:
- k = {3.14}; // error: narrowing conversion
- vector<int> vi; // initially empty
- vi = {0,1,2,3,4,5,6,7,8,9}; // vi now has ten elements, values 0 through 9
- 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.
- 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
- side with the elements in the lift on the right-hand side.
- #Assignment is Right Associative
- Unlike the other binary operators, assignment is right associative:
- int ival, jval;
- ival = jval = 0; // ok: each assigned 0
- 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:
- int ival, *pval; // ival is an int; pval is a pointer to int
- ival = *pval = 0; // error: cannot assign the value of a pointer to an int
- string s1, s2;
- s1 = s2 = "OK"; // string literal "OK" converted toa string
- #Assignment Has Low Precedence
- 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
- loop. We want to call a function until it returns a desired value-say, 42:
- // a verbose and therefore more error-prone way to write this loop
- int i = get_value(); // get the first value
- while ( i != 42)
- {
- // do something..
- i = get_value(); // get remaining values
- }
- 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
- int i;
- // a better way to write our loop---what the condition does is no clearer
- while ((i = get_value()) != 42)
- {
- // do something...
- }
- #4.2 Increment and Decrement Operators
- 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
- arithmetic.
- 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)
- the operand but yield a copy of the original, unchaged value as its result:
- int i = 0, j;
- j = ++i; // j = 1, i = 1: prefix yields the incremented value
- j = i++; // j = 1, i = 2: postfix yields and unincremented value
- 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.
- #Combining Dereference and Increment in a Single Expression
- 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.
- 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:
- auto pbeg = v.begin();
- // print elements up to the first negative value
- while (pbeg != v.end() && *pbeg >= 0)
- {
- cout << *pbeg++ << endl; // print the current value and advance pbeg
- }
- 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
- the element to which pbeg originally pointed and increments pbeg.
- 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,
- if the sequence had no negative values, we would attempt to dereference one too many elements.
- // the behavior of ths follow loop is undefined!
- while (beg != s.end() && !isspace(*beg))
- {
- *beg = toupper(*beg++); // error: this assignment is undefined
- }
- 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
- *beg = toupper(*beg); // execution if left-hand side is evaluted first
- *(beg + 1) = toupper(*beg); // execution if right-hand side is evaluted first
- or it might evalute in yet some other way.
- #4.6 The Member Access Operators
- 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:
- string s1 = "a string", *p = &s1;
- auto n = s1.size(); // run the size member of the string s1
- n = (*p).size(); // run size on the object to which p points
- n = p->size(); // equivalent to (*p).size()
- 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:
- // run the size member of p, then dereference the result!
- *p.size(); // error: p is a pointer and has no member named size
- 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.
- #The Conditional Operator
- The condition operator (the <?: operator) lets us embed simple if-else logic inside an expression. The conditional operator has the following form:
- cond ? expr : expr;
- 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;
- otherwise, expr2 is evaluted. As one example, we can use a conditional operator to determine whether a grade is pass or fail:
- string finalgrade = (grade < 60) ? "fail" : "pass";
- #Nesting Conditional Operations
- 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
- three-way test to indicate whether a grade is a high pass, an ordinary pass, or fail:
- finalgrade = (grade > 90) ? "high pass" : (grade < 60) ? "fail" : "pass";
- 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
- whether the grade is less than 60. if so, the ? branch is evaluated and yields "fail". if not, the : branch returns "pass".
- 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
- conditional expression.
- #Using A Conditional Operator In An Output Expression
- 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
- another value, depeneding on the result of a condition. An incompletely parenthesized conditional operator in an output expression can have surprising results:
- cout << ((grade < 60) ? "fail" : "pass"); // prints pass or fail
- cout << (grade < 60) ? "fail" : "pass"; // prints 1 or 0!
- cout << grade < 60 ? "fail" : "pass"; // error: compares cout to 60
- 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
- conditional operator. That is, the second expression is equivalent to
- cout << (grade < 60); // prints 1 or 0
- cout ? "fail" : "pass"; // test cout and then yield one of the two literals
- // depending on whether cout is true or false
- The last expression is an error because it is equivalent to
- cout << grade; // less-than has lower precedence than shift, so print grade first
- cout < 60 ? "fail" : "pass"; // then compare cout to 60!
- #4.8 The Bitwise Operators
- 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
- a flexibly sized collection of bits.
- 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.
- #Table 4.3 Bitwise Operators (left Associative)
- Operator Function Use
- ~ bitwise NOT ~expr
- __________________________________________
- << left shift expr1 << expr2
- >> right shift expr1 >> expr2
- __________________________________________
- & bitwise AND exer1 & expr2
- __________________________________________
- ^ bitwise XOR expr1 ^ expr2
- __________________________________________
- | bitwise OR expr1 | expr2
- 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.
- ****Warning****
- Because there are no guarantees for how the sign bit is handled, we strongly recommend using unsigned types with the bitwise operators.
- #Bitwise Shift Operators
- 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
- 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
- the result. Otherwise, the operation is undefined. The bits are shifted left (<<) or right (>>). Bits that are shifted off the end are discarded:
- // These illustrations have the low-order bit on the right
- // These examples assume char has 8 bits and int has 32
- // 0233 is an octal literal
- unsigned char bits = 0233; 1 0 0 1 1 0 1 1
- bits << 8 // bits promoted to int and then shifted left by 8 bits
- 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
- bit s<< 31 // left shifts 31 bits, left-most bits discarded
- 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
- bits >> 3 // right-shift 3 bits, 3 right-most bits discarded
- 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
- 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
- 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.
- #Bitwise NOT Operator
- 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
- unsigned char bits = 0227; 1 0 0 1 0 1 1 1
- ~bits
- 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
- 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
- in the promoted value are inverted.
- #Bitwise AND, OR, XOR Operators
- The AND (&), OR (|), and XOR (^) operators generate new values with the bit pattern composed from its two operands
- unsigned char b1 = 0145; 0 1 1 0 0 1 0 1
- unsigned char b2 = 0257; 1 0 1 0 1 1 1 1
- b1 & b2 24 high-order bits all 0 | 0 0 1 0 0 1 0 1
- b1 | b2 24 high-order bits all 0 | 1 1 1 0 1 1 1 1
- b1 ^ b2 24 high-order bits all 0 | 1 1 0 0 1 0 1 0
- 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
- 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.
- #Using Bitwise Operators
- 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
- a given test. We might represent each quiz in an unsigned integral value
- unsigned long quiz1 = 0; // we'll use this value as a collection of bits
- 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.
- 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
- has only bit 27 turend on. If we use bitwise OR that value with quiz1, all the bits except bit 27 will remain unchanged.
- 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.
- We can obtain a value indicating that student 27 passed by using the left-shift operator and an unsigned long integer literal 1:
- 1UL << 27; // generates a value with only bit number 27 set
- 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.
- Next we OR this value with quiz1. Because we want to update the value of quiz1, we use a compound assignment:
- quiz1 |= 1UL << 27; // indicating studnet number 27 passed
- The |= operator executes analogously to how += does. it is equivalent to
- quiz1 = quiz1 | 1UL << 27; // equivalent to quiz1 | = 1UL << 27
- 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
- AND this value with quiz1 to turn off just that bit:
- quiz1 &= ~(1UL << 27); // student number 27 failed
- 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
- this value with quiz1, all except bit 27 will remain unchanged.
- Finally we might want to know how the student at position 27 fared:
- bool status = quiz1 & (1UL << 27); // how did student number 27 do?
- 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.
- #Shift Operators (aka IO Operators) Are Left Associative
- 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,
- programmers need to understand the precedence and associativity of the shift operators even if they never use them with their built-in meaning.
- Because the shift operators are left associative, the expression
- cout << "hi" << " there" << endl;
- executes as
- ( (cout << "hi") << " there" ) << endl;
- 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
- grouping of operators with lower precedence.
- cout << 42 + 10; // ok: + has higher precedence, so the sum is printed
- cout << (10 < 42); // ok: parentheses force intended grouping: prints 1
- cout << 10 < 42; // error: attempt to compare cout to 42!
- The last cout is interpreted as
- (cout << 10) < 42;
- which says to "write 10 onto cout and then compare the result of that operation (i.e. cout) to 42."
- #4.9 The sizeof Operator
- 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:
- sizeof (type)
- sizeof expr
- 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:
- Sales_data data, *p;
- sizeof(Sales_data); // size required to hold an object of type Sales_data
- sizeof data; // size of data's type, i.e. sizeof(Sales_data)
- sizeof p; // size ofa pointer
- sizeof *p; // size of the type to which p points, i.e. sizeof(Sales_data)
- sizeof data.revenue; // size of the type of Sales_data's revenue member
- sizeof Sales_data::revenue; // alternative way to get the size of revenue
- 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
- need to fetch the member to know its size.
- The result of applying sizeof depends in part on the type involved:
- sizeof char or an expression of type char is guaranteed to be 1.
- sizeof a reference type returns the size of an object of the reference type.
- sizeof a pointer returns the size needed to hold a pointer.
- sizeof a dereferenced pointer returns the size of an object of the type to which the pointer points; the pointer need not be valid.
- 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.
- 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.
- 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:
- // sizeof(ia)/sizeof(*ia) returns the number of elements in ia
- constexpr size_t sz = sizeof(ia)/sizeof(*ia);
- int arr2[sz]; // ok sizeof returns a constant expression
- Implicit Conversion: C++ Defines a set of conversions to transform the operands of a different types to one common type. Carried out automatically.
- 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
- converted to double, floating-point addition is done, and the result is a double.
- int ival = 3.541 + 3; // 3 is promoted to float; 3.541 + 3 is then converted to int
- #When Implicit Conversions Occurs
- The compiler automatically converts operands in the following Circumstatnces
- In most expression, values of integral types smaller than int are first promoted to an appropriate larger integral type.
- In conditions, nonbool expressions are converted to bool.
- 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.
- In arithmetic and relational expressions with operands of mixed types, the types are converted to a common type.
- As we'll see in Chapter 6, conversions also happen during function calls.
- #4.11.1 The Arithmetic Conversions
- 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
- 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.
- #Integral Promotions
- 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
- value is promoted to unsigned int. As we've seen many times, a bool that is false promotes to 0 and true to 1.
- 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.
- #Operands of Unsigned Type
- 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
- on the machine.
- 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.
- 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
- 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.
- 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
- 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,
- then the unsigned int will be converted to long.
- #Understanding Arithmetic Conversions
- One way to understand the arithmetic conversions is to study lots of examples:
- bool flag; char cval;
- short sval; unsigned short usval;
- int ival; unsigned int uival;
- long lval; unsigned long ulval;
- float fval; double dval;
- 3.14159L + 'a'; // 'a' promoted to int, then that int converted to long double
- dval + ival; // ival converted to double
- dval + fval; // fval converted to double
- ival = dval; // dval converted (by truncation) to int
- flag = dval; // if dval is 0, then flag is false, otherwise true
- cval + fval; // cval promoted to int, then that int converted to float
- sval + cval; // sval and cval promoted to int
- cval + lval; // cval converted to long
- ival + ulval; // ival converted to unsigned long
- usval + ival; // promotion depends on the size of the unsigned short and int
- uival + lval; // conversion depends on the size of unsigned int and long
- 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.
- #4.11.2 Other Implicit Conversions
- In addition to the arithmetic conversions, there are several additional kinds of implicit conversions. These include:
- 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:
- int ia[10]; // array of ten ints
- int* ip = ia; // convert ia to a pointer to the first element
- 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.
- 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*
- 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)
- 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:
- string s, t = "a value"; // character string literal converted to type string
- while (cin >> s) // while condition converts cin to bool
- #4.11.3 Explicit Conversions
- 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:
- int i, j;
- double slope = i/j;
- 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.
- #Named Casts
- The cast-name may be one of <static_cast>, <dynamic_cast>, <const_cast>, and <reinterpret_cast>.
- cast-name<type> (expression);
- cast-name determines the type of conversion is performed.
- <type> is the target type of the conversion. If type is a reference, then the result is an lvalue.
- (expression) is the value to tbe cast.
- #static_cast
- 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:
- // cast used to force floating-point division
- double slope = static_cast<double>(j)/i;
- // slope is type double, j is converted to type double and divided by i (type int)
- static_cast is often used when a larger arithmetic type is assigned toa smaller type.
- 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:
- void* p = &d; // ok: address of any nonconst object can be stored in a void*
- // ok: converts void* back to the original pointer type
- double *dp = static_cast,double*>(p);
- 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,
- 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.
- #const_cast
- A const_cast changes only a low-level const in its operand:
- const char *pc;
- char *p = const_cast<char*>(pc); // ok: but writing through p is undefined
- 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
- 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.
- 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:
- const char *cp;
- // error: static_const can't cast away const
- char *q = static_cast<char*>(cp);
- static_cast<string>(cp); // ok: converts string literal to string
- const_cast<string>(cp); // error: const_cast only changes constness
- A const_cast is most useful in the context of overloaded functions.
- #reinterpret_cast
- A reinterpret_cast generally performs a low-level reinterpretation of the bit patters of its operands. As an example, given the following cast
- int *ip;
- char *pc = reinterpret_cast<char*>(ip);
- 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:
- string str(pc);
- is likely to result in bizarre run-time behavior.
- 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
- 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
- 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
- in which pc is used to initialize a string.
- #4.12 Operator Precedence Table
- #Table 4.4 Operator Precedence
- Associativity
- And Operator Function Use See Page
- L :: global scope ::name 286
- L :: class scope class:name 88
- L :: namespace scope namespace:name 82
- ______________________________________________________________________________
- L . member selectors object.member 23
- L -> member selectors pointer->member 110
- L [] subscript expr[expr] 116
- L () function call name(expr_list) 23
- L () type construction type(expr_list) 164
- _______________________________________________________________________________
- R ++ postfix increment lvalue++ 147
- R -- postfix decrement lvalue-- 147
- R typeid type ID typeid(type) 826
- R typeid run-time type ID typeid(expr) 826
- R explicit cast type conversion cast_name<type>(expr) 162
- _______________________________________________________________________________
- R ++ prefix increment ++lvalue 147
- R -- prefix decrement --value 147
- R ~ bitwise NOT ~expr 152
- R ! logical NOT !expr 141
- R - unary minus -expr 140
- R + unary plus +expr 140
- R * derefence *expr 53
- R & address-of &lvalue 52
- R () type conversion (type)expr 164
- R sizeof size of object sizeof expr 156
- R sizeof size of type sizeof(type) 156
- R sizeof.. size of parameter pack sizeof...(name) 700
- R new allocate object new type 458
- R new[] allocate array new type[size] 458
- R delete deallocate object delete expr 460
- R delete[] deallocate array delete[] expr 460
- R noexcept can expr throw noexcept (expr) 780
- _______________________________________________________________________________
- L ->* ptr to member select ptr->*ptr_to_member 837
- L .* ptr to member select obj.*ptr_to_member 837
- _______________________________________________________________________________
- L * multiply expr * expr 139
- L / divide expr / expr 139
- L & modulo (remainder) expr % expr 139
- _______________________________________________________________________________
- L + add expr + expr 139
- L - subtract expr - expr 139
- ________________________________________________________________________________
- L << bitwise shift left expr << expr 152
- L >> bitwise shift right expr >> expr 152
- ________________________________________________________________________________
- L < less than expr < expr 141
- L <= less than or equal expr <= expr 141
- L > greater than expr > expr 141
- L >= greater than or equal expr >= expr 141
- ________________________________________________________________________________
- L == equality expr == expr 141
- L != inequality expr != expr 141
- ________________________________________________________________________________
- L & bitwise AND expr & expr 152
- ________________________________________________________________________________
- L ^ bitwise XOR expr ^ expr 152
- ________________________________________________________________________________
- L | bitwise OR expr | expr 152
- ________________________________________________________________________________
- L && logical AND expr && expr 141
- ________________________________________________________________________________
- L || logical OR expr || expr 141
- ________________________________________________________________________________
- R ?: conditional expr ? expr : expr 151
- ________________________________________________________________________________
- R = assignment lvalue = expr 144
- ________________________________________________________________________________
- R *=, /=, %=, compound assign lvalu += expr, etc 144
- R +=, -=, 144
- R <<=, >>=, 144
- R &=, |=, ^= 144
- ________________________________________________________________________________
- R throw throw exception throw expr 193
- ________________________________________________________________________________
- L , comma expr, 157
- /*Chapter 5*/
- #Null Statements
- The simples statement is the empty statement, also known as a <null statement>. A null statement is a single semicolon:
- ; // null statement
- 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
- we read until we encounter a particular value:
- // read until hit end-of-file or find an input equal to sought
- while (cin >> s && s != sought)
- ; // null statement
- #Beware of Missing or Extraneous Semicolons
- 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:
- // disaster: extra semicolon: loop body is this null statement
- while (iter != svec.end()) ; // the while body is the empty statement
- ++iter; // incremenet is not part of the loop
- #Compound Statements (Blocks)
- 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
- and in blocks nested inside that block. Names are visible from where they are defined until the end of the (immediately) enclosing block.
- while (val <= 10) {
- sum += val; // assigns sum + val to sum
- ++val // add 1 to val
- }
- 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:
- while (cin >> s && s != sought)
- {} // empty block
- #5.3.1 The if Statement
- 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
- if (condition)
- statement
- else
- statement2
- #Dangling Else
- 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?
- 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
- else is matched with the closest preceding unmatched if.
- 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:
- // WRONG: execution does NOT match indentation; the else goes with the inner if
- if (grade % 10 >= 3)
- if (grade % 10 > 7)
- lettergrade += '+'; // grades ending in 8 or 9 get a +
- else
- lettergrade += '-'; // grades ending in 3, 4, 5, 6 will get a minus!
- 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,
- 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:
- // indentation matches the execution path, not the programmer's intent
- if (grade % 10 >= 3)
- if (grade % 10 > 7)
- lettergrade += '+'; // grades ending in 8 or 9 get a +
- else
- lettergrade += '-'; // grades ending in 3, 4, 5, 6 will get a minus!
- #Controlling The Execution Path With Braces
- We can make the else part of the outer if by enclosing the inner if in a block:
- // add a plus for grades that end in 8 or 9 and a minus for those ending in 0, 1, or 2
- if (grade % 10 >= 3) {
- if (grade % 10 > 7)
- lettergrade += '+'; // grades ending in 8 or 9 get a +
- } else // curlies force the else to go with the outer if
- lettergrade += '-'; // grades ending in 0, 1, or 2 will get a minus
- #5.3.2 The switch Statement
- A <switch statement> provides a convenient way of selecting among a (possibly large) number of fixed alternatives.
- 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
- value associated with each case.
- The case keyword and its associated value together are known as the <case label>. case labels must be integral constant expressions:
- char ch = getVal();
- int ival = 42;
- switch(ch) {
- case 3.14: // error: noninteger as case label
- case ival: // error: nonconstant as case label
- // ...
- }
- 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.
- #Control Flow within a switch
- 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
- 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.
- 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
- break statement, allowing the program to fall through multiple case labels.
- For example, we might want to count only the total number of vowels:
- unsigned vowelCnt = 0;
- // ...
- switch (ch) {
- // any occurence of a, e, i , o, or u increments vowlCnt
- case 'a':
- case 'e':
- case 'o':
- case 'u':
- ++vowelCnt;
- break;
- }
- 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:
- switch (ch) {
- // alternative legal syntax
- case 'a': case 'e': case 'i': case 'o': case 'u':
- ++vowelCnt;
- break;
- }
- #The default Label
- 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
- name otherCnt, in the default case:
- // if ch is a vowel, increment the appropriate counter
- swwitch (ch) {
- case 'a': case 'e': case 'i': case 'o': case 'u':
- ++vowelCnt;
- break;
- default:
- ++otherCnt;
- break;
- }
- 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.
- #Variable Definitions inside the Body of a switch
- 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
- question: What happens if the code that is skipped includes a variable definition?
- 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:
- case true:
- //this switch statement is illegal because these initializations might be bypassed
- string file_name; // error: control bypass an implicitly initialized variable
- int ival = 0; // error: control bypasses an explicitly initialized variable
- int jval; // ok: because jval is not initialized
- break;
- case false:
- // ok: jval is in scope but uninitialized
- jval = next_num(); // ok: assign a value to jval
- if (file_name.empty()) // file_name is in scope but wasn't initialized
- // ....
- 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
- 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.
- 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:
- case true: {
- // ok: declaration statemenet within a statement block
- string file_name = get_file_name();
- // ...
- }
- break;
- case false:
- if (file_name.empty()) // error: file_name is not in scope
- #5.4.1 The while statement
- A <while statement> repeatedly executes a target statement as long as a condition is true. Its syntactic form is
- while (condition)
- statement
- #5.4.2 Traditional for Statement
- The syntactic form of the <for statmeent> is:
- for (init-statement condition; expression)
- statement
- #Multiple Definitions in the for Header
- 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
- the elements of a vector on the end as follows:
- // remember tha size of v and stop when we get to the original last element
- for (decltype(v.size()) i = 0, sz = v.size(); i != sz; ++i)
- v.push_back(v[i]);
- In thise loop we define both the index, i, and the loop control, sz, in init-statement.
- #Omitting Parts of the for Header
- A for header can omit any (or all) of init-statement, condition, or expression.
- We can use a null statement for init-statement when we an initialization is unnecessary.
- #5.4.3 Range for Statement
- 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:
- for (declaration : expression)
- statement
- 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.
- #5.4.4 The do while Statement
- 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:
- do
- statement
- while (condition);
- 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
- while statement.
- We can write a program that (indefinitely) does sums using a do while:
- // repeatedly ask the user for a pair of numbers to sum
- string rsp; // used in the condition; can't be defined inside the do
- do {
- cout << "Please enter two values: ";
- int val1 = 0, val2 = 0;
- cin >> val1 >> val2;
- cout << "The sum of " << val1 << " and " << val2 << " = " << val1 + val2 << "\n\n"
- << "more? Enter yes or no: ";
- cin >> rsp;
- } while (!rsp.empty() && rsp[0] != 'n');
- 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:
- do {
- // ...
- mumble(foo);
- } while (int foo = get_foo()); // error: declaration in a do condition
- #5.5.1 The break Statement
- A <break statement> terminates the nearest enclosing while, do while, for, or switch statement. Execution resumes at the statement immediately following the terminated statement.
- string buf;
- while (cin >> buf && !buf.empty()) {
- switch (buf[0]) {
- case '-':
- // process up to the first blank
- for (auto it = buf.begin() + 1; it != buf.end(); ++it) {
- if (*it == ' ')
- break; // #1, leaves the for loop
- // ...
- }
- // break #1 transfers control here
- // remaining '-' processing:
- break; // #2, leaves the switch statement
- case '+';
- // ...
- } // end switch
- // end of switch: break #2 transfers control here
- } // end while
- 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
- statement following the for, which might be additional code to handle a hyphen or the break that completes that section.
- 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.
- #5.5.2 The continue Statement
- 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
- 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.
- 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
- range for, execution continues by initializing the control variable from the next element in the sequence.
- 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:
- string buf;
- while (cin >> buf && !buf.empty()) {
- if (buf[0] != '_')
- continue; // get another input
- // still here? the input starts with an underscore; process buf ...
- }
- #5.5.3 The goto Statement
- A <goto statement> provides an unconditional jump from the goto to another statement in the same function.
- The syntactic form of a goto statement is
- goto label;
- where label is an indentifier that identifies a statement. A <labeled statement> is any statement that is preceded by an identifier by a colon:
- end: return; // labeled statement; may be the target of a goto
- 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
- statmeent to which it transfers control must be in the same function.
- 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:
- // ...
- goto end;
- int ix = 10; // error: goto bypasses an initialized variable definition
- end:
- // error: code here could use ix but the goto bypassed its declaration
- ix = 42;
- 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:
- // backward jump over an initialized variable definition is okay
- begin:
- int sz = get_size();
- if (sz <= 0) {
- goto begin;
- }
- 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.
- #5.6 try Blocks and Exception Handling
- 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.
- 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
- 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
- stops processing.
- 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,
- the handling part might alert an operator.
- Exception handling supports this cooperation between the detecting and handling parts of a program. In C++, exception handling involves
- <throw expression>, which the detecting part uses to indicate that is encountered something it can't andle. We say that a throw <raises> exception.
- <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
- one of the catch clases. Because they "handle" the exception, catch clauses are also known as <exception handlers>.
- A set of <exception classes> That are used to pass information about what happened between a throw and an associated catch.
- #5.6.1 A throw Expression
- 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
- followed by a semicolon, making it into an expression statement.
- // first check that item 1 and item2 represent the same book
- if (item1.sibn() == item2.isbn()){
- cout << item1 + item2 << endl;
- return 0; // indicate success
- } else {
- cerr << "Data must refer to the same ISBN" << endl;
- return -1; // indicate failure
- }
- 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:
- // first check that the data are from the same item
- if (item1.isbn() != item2.isbn())
- throw runtime_error("Data must refer to same ISBN");
- // if we're still here, the ISBNs are the same
- cout << item1 + item2 << endl;
- 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
- string. That string provides additional information about the problem.
- #5.6.2 The try Block
- The general form of a try block is
- try {
- program-statements
- } catch (exception-declaration) {
- handler-statements
- } catch (exception-declaration) {
- handler-statements
- } // ...
- 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
- 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.
- 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
- the block-in particualr, they are not accessible to the catch clause.
- #Writing a Handler
- 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
- that interacts with the user might contain code something like the following to handle the exception that was thrown:
- while (cin >> item1 >> item2) {
- try {
- // execute code that will add the two Sales_items
- // if the addition fails, the code throws a runtime_error exception
- } catch (runtime_error err) {
- // remind the user that the ISBNs must match and prompt for another pair
- cout << err.what() << "\nTry again? Enter y or n" << endl;
- char c;
- cin >> c;
- if (!cin || c == 'n')
- break;
- }
- }
- 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.
- 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
- 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
- to the while condition for the next iteration.
- 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
- 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
- secition threw an exception, then this catch would print
- Data must refer to same ISBN
- Try again? Enter y or n
- #Funcions Are Exited during the Search for a Handler
- 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
- own try, and so on.
- 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
- 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.
- 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.
- 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
- is called and the program is exited.
- #5.6.3 Standard Exceptions
- 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:
- 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.
- The stdexcept header defines several general-purpose exception classes, which are listed in Table 5.1
- The new header defines the bad_alloc exception type, which we cover in 12.1.2.
- The type_info header defines the bad_cast exception type, which we cover in 19.2.
- #Table 5.1 Standard Exception CLasses Defined in <stdexcept>
- exception The most general kind of problem
- runtime_error Problem that can be detected only at run time.
- range_error Run-time error: result generated outside the range of values that are meaningful
- overflow_error Run-time error: computations that overflowed.
- underflow_error Run-time error: computation that underflowed.
- logic_error Error in the logic of the program
- domain_error Logic error: argument for which no result exists
- invalid_argument Logic error: inappropriate argument
- length_error Logic error: attempt to create an object larger than the maximum size for that type.
- out_of_range Logic error: used a value outisde the valid range.
- The library exception classes have only a few operations. We can create, copy, and assign objects of any of the exception types.
- 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.
- 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
- an intialize. That initalize is used to provide additional information about the error that occurred.
- 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
- textual description of the exception thrown.
- /* Chapter 6 */
- 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
- different functions.
- #Calling a Function
- 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.
- #Parameters and Arguments
- 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,
- 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.
- #Function Parameter List
- 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
- parameters:
- void f1(){ /* ... */ } // implicit void parameter list
- void f2(void){ /* ... */ } // explicit void parameter list
- 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
- 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.
- #Function Return Type
- 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
- 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.
- #Automatic Objects
- 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
- 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.
- 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.
- #Local static Objects
- 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
- through the object's definition. Local statics are not destroyed when a function ends; they are destroyed when the program terminates.
- As a trivial example, here is a function that has that counts how many times it is called:
- size_t count_calls()
- {
- static size_t ctr = 0; // value will persist across calls
- return ++ctr;
- }
- int main()
- {
- for (size_t i = 0; i!= 10; ++i)
- cout << count_calls() << endl;
- return 0;
- }
- #6.1.2 Function Declarations
- 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
- that is not defined so long as we never use that function.
- 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.
- 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
- what the function does:
- // parameter names chosen to indicate that the iteration denotes a range of values to print
- void print(vector<int>::const_iterator beg, vector<int>::const_iterator end);
- 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>.
- #Function Declarations Go In Header Files
- 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.
- #Pointer Parameters
- 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
- access to the object to which that pointer points.
- The same behavior applies to pointer parameters:
- // function that takes a pointer and sets the pointed-to value to zero
- void reset(int *ip)
- {
- *ip = 0; // changes the value of the object to which ip points
- ip = 0; // changes only the local copy of ip; the argument is unchanged
- }
- After a call to reset, the object to which the argument points will be 0, but the pointer argument itself is unchanged:
- int i = 42;
- reset(&i) // changes i but not the address of i
- cout << "i = " << i << endl;
- #6.2.2 Passing Arguments by Reference
- Reference parameters exploit this behavior. They are often used to allow a function to change the value of one or more of its arguments.
- As one example, we can rewrite our reset program from the previous section to take a reference instead of a pointer:
- // function that takes a reference to an int and sets the given object to zero
- void reset(int &i) // i is just another name for the object passed to reset
- {
- i = 0; // changes the value of the object to which i refers
- }
- When we call this version of reset, we pass an object directly; there is no ned to pass its address:
- int j = 42;
- reset(j); // j is passed by reference; the value in j is changed
- cout << "j = " << j << endl; // prints j = 0
- In this call, the parameter i is just another name for j. Any use of i inside reset is a use of j.
- #Using Reference to Avoid Copies
- 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
- on objects of a type that cnanot be copied.
- // compare the length of two strings
- bool isShorter(const string &s1, const string &s2)
- {
- return s1.size() < s2.size();
- }
- #Using Reference Paramters to Return Additional Information
- 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
- 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.
- #6.2.3 const Parameters and Arguments
- When we use parameters that are const, it is important to remember the discussion of top-level const from 2.4.3.
- 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
- that has a top-level const:
- void fcn(const int i) { /* fcn can read but not write to i */ }
- 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:
- void fcn(const int i) { /* fcn can read but not write to i */ }
- void fcn(int i) { /* ... */ } // error redefines fcn(int)
- #Pointer or Reference Parameter and const
- 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,
- and a plain reference must be initialized from an object of the same type
- Exactly the same initialization rules apply to parameter passing:
- int i = 0;
- const int ci = i;
- string::size_type ctr = 0;
- reset(&i); // calls the version of reset that has an int* parameter
- reset(&ci); // error: can't initialize an int* from a pointer to a const int object
- reset(i); // calls the version of reset that has an int& parameter
- reset(ci); // error: can't bind a plain reference to the const object ci
- reset(42); // error: can't bind a plain reference to a literal
- reset(ctr); // error: types don't match; ctr has an unsigned type
- find_char("Hello World!", 'o', ctr); // ok: find_char's first parameter is a reference to const
- #6.2.4 Array Parameters
- 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
- 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.
- Even though we cannot pass an array by value, we can write a paramter that looks like an array:
- // despite appearances, these three declarations of print are equal
- // each function has a single parmater of type const int*
- void print(const int*);
- void print(const int[]); // shows the intent that the function takes an array
- void print(const int[10]); // dimension for documentation purpose (at best)
- 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*:
- int i = 0, j[2] = {0, 1};
- print(&i); // ok: &i is int *
- print (j); // ok: j is converted to an int* that points to j[0]
- 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.
- #Using a Marker to Specify the Extend of an Array
- 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
- is followed by a null character. Functions that deal with C-style strings stop processing the array when they see a null character:
- void print(const char *cp)
- {
- if (cp) // if cp is not a null character
- while (*cp) // so long as the character it points to is not a null character
- cout << *cp++;
- }
- #Using the Standard Library Conventions
- 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
- in Part II. Using this approach, we'll print the elements in an array as follows:
- void print(const int *beg, const int *end)
- {
- // print every element starting at beg up to but not including end
- while (beg != end)
- cout << *beg++ << endl; // print the current element and advance the pointer
- }
- 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.
- To call this function, we pass two pointers-one to the first element we want to print and one past the last element:
- int j[2] = {0, 1}
- // j is converted to a pointer to the first element in j
- // the second argument is a pointer to one past the end of j
- print(begin(j), end(j)); // begin and end functions
- #Explicitly Passing a Size Paramter
- 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:
- // const int ia[] is equivalent to const int *ia
- // size is passed explicitly and used to control access to elements of ia
- void print(const int ia[], size_t size)
- {
- for (size_t i = 0; i != size; ++i){
- cout << ia[i] << endl;
- }
- }
- 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:
- int j[] = {0, 1}; // int array of size 2
- print(j, end(j) - begin(j));
- #Array Referene Parameters
- 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:
- // ok: parameter is a reference to an array; the dimension is part of the type
- void print(int (&arr)[10])
- {
- for auto (elem : arr)
- cout << elem << endl;
- }
- ***Note****
- The parentheses around &arr are necessary.
- f(int &arr[10]) // error: declares arr as an array of referenes
- f(int (&arr)[10]) // ok: arr is a reference to an array of ten ints
- 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
- only for an array of exactly ten ints.
- #Passing a Multidimensional Array
- Recall that there are no multidimesional arrays in C++. Instead, what appears to be multidimensional array is n array of arrays.
- 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
- subsequent) dimension is part of the element type and must be specified:
- // matrix points to the first element in an array whose elements are arrays of ten ints
- void print(int (*matrix)[10], int rowSize) { /* ... */ }
- declares matrix as a pointer to an array of ten ints.
- 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:
- // equivalent definition
- void print(int matrix[][10], int rowSize) { /* ... */ }
- declares matrix to be what looks like a two-dimensional array. In fact, the parameter is a poitner to an array of ten ints.
- #6.2.5 main: Handling Command-Line Options
- 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:
- int main() { ... }
- 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
- prog, we might pass options to the program as follows:
- prog -d -o ofile data0
- Such command-line options are passed to main in two (optional parameters):
- int main(int argc, char *argv[]) { ... }
- 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
- int main(int argc, char **argv) { ... }
- indicating that argv points to a char*.
- 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
- to be 0.
- Given the previous command line, argc would be 5, and argv would hold the following C-style character string:
- argv[0] = "prog"; // or argv[0] might point to an empty string
- argv[1] = "-d";
- argv[2] = "-o";
- argv[3] = "ofile";
- argv[4] = "data0";
- argv[5] = 0;
- #6.2.6 Functions with Varying Parameters
- 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
- 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.
- 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
- special kind of function, known as a variadic template, which we'll cover in 16.4.
- 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
- in programs that need to interface to C functions.
- #Initializer_list Parameters
- 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
- initializer_list header. The operations that initializer_list provides are listed in Table 6.1.
- #Table 6.1 Operations on initializer-lists
- initializer_list<T> lst; // default initializer; an empty list of elements of type T
- 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
- lst2(lst) // copying or assigning an intializer_list does not copy the elements
- lst2 = lst // in the list. After the copy, the original and the copy share the elements.
- lst.size() // Number of elements in the list.
- lst.begin() // Retruns a pointer to the first and one past the last element in lst
- lst.end()
- 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:
- initializer_list<string> ls; // initializer_list of strings
- initailizer_list<int> l1; // initializer_list of ints
- 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.
- We can write our function to produce error messages from a varying number of arguments as follows:
- void error_msg(initializer_list<string> il)
- {
- for (auto beg = il.begin() ; beg != il.end(); ++beg)
- cout << *beg << " " ;
- cout << endl;
- }
- 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
- 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.
- When we pass a sequence of values to an initializer_list parameter, we must enclose the sequence in curly braces:
- // expected, actual are strings
- if (expected != actual)
- error_msg({"functionX", expected, actual});
- else
- error_msg({"functionX", "okay"});
- Here we're calling the same function error_msg, passing three values in the first call and two values in the second.
- 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
- in addition to an initializer_list as follows:
- void error_msg(ErrCode e, initializer_list<string> il)
- {
- cout << e.msg() << " : ";
- for (const auto &elem : il)
- cout << elem << " ";
- cout << endl;
- }
- To call this version, we need to revise our calls to pass an ErrCode argument:
- if (expected != actual)
- error_msg(ErrCode(42), {"functionX", expected, actual});
- else
- error_msg(ErrCode(0), {"FunctionX", "okay"});
- #Ellipsis Parameters
- 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
- to use varargs.
- An ellipsis parameter may appear only as the last elemnt in a parameter list and may take either two forms:
- void foo(parm_list, ...):
- void foo(...);
- #How Values Are Returned
- 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
- function call.
- 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
- the plural version of the word if the counter is greater than 1:
- // return the plural version of word if ctr is greater than 1
- string make_plural(size_t ctr, const string &word, const string &ending)
- {
- return (ctr > 1) ? word + ending : word;
- }
- 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
- adding word and ending.
- 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
- to the shorter of its two string parameters:
- // return a reference to the shorter of two stringstream
- const string &shorterString(const string &s1, const string &s2)
- {
- return s1.size() < s2.size() ? s1 : s2;
- }
- 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.
- #Never Return a Reference or Pointer to a local Object
- When a function completes, its storage is freed. After a function terminates, references to local objects refer to memory that is no longer valid:
- // disaster: this function returns a reference to a local object
- const string &mainip()
- {
- string ret;
- // transform ret in some way
- if (!ret.empty())
- return ret; // WRONG: returning a reference to a local object!
- else
- return "Empty"; // WRONG: "Empty" is a local temporary string
- }
- 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
- 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
- temporary resides is freed when the function ends. Both returns refer to memory that is no longer available.
- #Functions That Return Class Types and the Call Operator
- 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
- 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.
- For example, we can determine the size of the shorter string as follows:
- // call the size of the string returned by shorterString
- auto sz = shorterString(s1, s2).size();
- 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
- left-hand operand of the second call operator.
- #Reference Returns are Lvalues
- 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
- 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:
- char &get_val(string &str, string::size_type ix)
- {
- return str[ix]; // get_val assumes the given index is valid
- }
- int main()
- {
- string s("a value");
- cout << s << endl; // prints a value
- get_val(s,0) = 'A'; // changes s[0] to A
- cout << s << endl; // prints A value
- return 0;
- }
- 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
- operand of the assignment operator.
- If the return type is a reference to const, then (as usual) we may not assign to the result of the call:
- shorterString("hi", "bye") = "x"; // error: return value is const
- #6.3.3 Returning a Pointer to an Array
- 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
- arrays can be intimidating. Fortunately, there are ways to simplify such delarations. The most straightforward way is to use a type alias:
- typedef int arrT[10]; // arrT is a synonym for the type array of ten ints
- using arrtT = int[10]; // equivalent declaration of arrT; see 2.5.1 (p 68)
- arrT* func(int i); // func returns a pointer to an array of ten ints
- 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.
- #Declaring a Function That Returns a Pointer to an Array
- To declare func without using a type alias, we must remember that the dimension of an array follows the name being defined:
- int arr[10]; // arr is an arry of ten ints
- int *pi[10]; // p1 is an arry of ten pointers
- int (*p2)[10] = &arr; // p2 points to an array of ten ints
- 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
- the dimension. Hence, the form of a function that returns a pointer to an array is:
- Type (*function(parameter_list))[dimension]
- 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
- them, we be defining a function that returns an array of pointers.
- As a concrete example, the following declares func without using a type alias:
- int (*func(int i))[10];
- To understand this declaration, it can be helpful to think about it as follows:
- -func(int) says that we can call func with an int argument
- -(*func(int)) says we can dereference the result of that call
- -(*func(int))[10] says that dereference the result of a call to func yields an array of size ten.
- -int (*func(int))[10] says the element type in that array is int.
- #Using a Trailing Return Type
- 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
- (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
- // fcn takes an int argument and returns a pointer to an array of ten ints
- auto func(int i) -> int(*)[10];
- 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.
- #Using decltype
- 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
- of its parameter:
- int odd[] = {1,3,5,7,9};
- int even[] = {0,2,4,6,8};
- // returns a pointer to an array of five int elements
- decltype(odd) *arrPtr(int i)
- {
- return (i % 2) ? &odd : &even; // returns a pointer to the array
- }
- 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
- 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.
- #6.4 Overloaded Functions
- 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:
- void print(const char *cp);
- void print(const int *beg, const int *end);
- void print(const int ia[], size_t size);
- 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:
- int j[2] = {0, 1};
- print("Hello World"); // calls print(const char*)
- print(j, end(j) - begin(j)); // calls print(const int*, size_t)
- print(begin(j), end(j)); // calls rpint(const int*, const int*)
- Defining Overloaded functions
- 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
- do the search. We can call lookup passing a value of any of several types:
- Record lookup(const Account&); // find by Account
- Record lookup(const Phone&); // find by Phone
- Record lookup(const Name&); // find by Name
- Account acct;
- Phone phone;
- Record r1 = lookup(acct); // call version that takes an Account
- Record r2 = lookup(phone); // call version that takes a Phone
- 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.
- 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.:
- Record lookup(const Account&);
- bool lookup(const Account&); // error: only the return type is different
- #Determining Wheter Two Parameter Types Differ
- Two parameter lists can be identical, even if they don't look the same:
- // each par declares the same function
- Record lookup(const Account &acct);
- Record lookup(const Account&); // parameter names are ignored
- typdef Phone Telno;
- Record lookup(const Phone&);
- Record lookup(const Telno&); // Telno and Pone are the same type
- In the first pair, the first declaration names its parameter. Parameter names are only a documentation aid. They do not change the parameter list.
- 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
- differ only in that one uses an alias and the other uses the type to which the alias correspondings are not different.
- #Overloading and const Parameters
- 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:
- Record lookup(Phone);
- Record lookup(const Phone); // redeclares Record lookup(Phone)
- Record lookup(Phone*);
- Record lookup(Phone* const); // redeclares Record looup(Phone*)
- In these declarations, the second declaration declares the same function as the first.
- 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:
- // functions taking const and nonconst references or pointers have different parameters
- // declarations for four independent, overloaded functions
- Record lookup(Account&); // function that takes a reference to Account
- Record lookup(const Account&); // new function that takes a const reference
- Record lookup(Account*); // new function, takes a pointer to account
- Record lookup(const Account*); // new function, takes a pointer to a const
- 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
- 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
- to nonconst.
- #const_cast and Overloaded
- 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:
- // return a reference to the short of two strings
- const string &shorterString(const string &s1, const string &s2)
- {
- return s1.size(0 < s2,size() ? s1 : s2;
- }
- 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
- that, when given nonconst arguments, would yield a plain reference. We can write this version fo our function using a const_cast:
- string &shorterString(string &s1, string s2)
- {
- auto &r = shorterString(const_cast<const string&>(s1), const_cast<const_string&>(s2));
- return const_cast<string&>(r);
- }
- 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
- to cast that string back to a plain string& in the return.
- #Calling an Overloaded Function
- 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
- 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.
- For now, what's important to realize is that for any given call to be an overloaded function, there are three possible outcomes:
- -The compiler finds exactly one function that is a <best match> for the actual arguments and generates code to call that function.
- -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>.
- -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>.
- #6.4.1 Overloading and Scope
- string read();
- void print(const string&);
- void print(double); // overloads the print function
- void fooBar(int ival)
- {
- bool read = false; // new scope: hides the outer declaration of read
- string s = read(0; // error: read is a bool variable, not a function
- // bad practice: usually it's a bad idea to dclare functions at local scope
- void print(int); // new scope: hides previous instances of print
- print("Value: "); // error: print(const string &) is hidden
- print(ival; // ok: print(int) is visible
- print(3.14); // ok: calls print(int); print(double is hidden)
- }
- 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
- 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.
- 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
- matched this call, is hidden and is not considered.
- 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.
- 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:
- void print(const string &);
- void brint(double); // overloads the print function
- void print(int); // another overloaded instance
- void fooBar2(int ival)
- {
- print("Value: "); // calls print(const strin g&)
- print(ival); // call print(int)
- print(3.14); // calls print(double)
- }
- #6.5.1 Default Arguments
- 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
- without that argument
- 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
- defaults. To accommodate both default and specified values we woudl declare our function to define the window as follows:
- typedef string::size_type sz: // typedef see 2.5.1
- string screen(sz) ht = 24, sz wid = 80, char backgrnd = ' ');
- 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
- parameters that follow it must also have default arguments.
- #Default Argument Initializers
- 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:
- // the declarations of wd, def, and ht must appear outside a function
- sz wd = 80;
- char def = ' ';
- sz ht();
- string screen9sz = ht(), sz = wd, char = def);
- string window = screen(); // calls screen(ht(),80,' ')
- 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:
- void f2()
- {
- def = '*'; // changes the value of a default argument
- sz wd = 100; // hides the outer definition of wd but does not change the default
- window = screen(); // calls screen(ht(), 80, '*')
- }
- #inline Functions Avoid Function Call Overhead
- A function specified as <inline> (usually) is expanded "in line" at each call. If shorterString were defined as inline, then this call
- cout << shorterString(s1, s2) << endl;
- (probably) would be expanded during compilation into something like
- cout << (s1.size() < s2,size() ? s1 : s2) << endl;
- The run-time overhead of making shorterString a function is thus removed.
- // inline version: find the shorter of two strings
- inline const string & shorterString(const string &s1, const string &s2,)
- {
- return s1.size() <= s2.size() ? s1 : s2;
- }
- #constexpr Functions
- 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,
- and the function body must contain exactly one return statement:
- constexpr int new_sz() { return 42; }
- constexpr int foo = new_sze(); // ok:: foo is a constant expression
- A constexpr function is permitted to return a value that is not a constant:
- // scale(arg) is a constant expression if arg is a constant expression
- constexpr size_t scale(size_t cnt) { return new_size() * cnt; }
- The scale function will return a constant expression if its argument is a constant expression but not otherwise:
- int arr[scale(2)]; // ok: scale(2) is a constant expression
- int i = 2; // i is not a constant expression
- int a2[scale(i)]; // error: scale(i) is not a constant expression
- #6.5.3 Aids for Debugging
- 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
- is completed and ready to ship, the debugging code is turned off. This approach uses two preprocessor facilites: assert and NDEBUG.
- #The assert Preprocessor Macro
- <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:
- assert(expr);
- 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.
- 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,
- we refer to assert, not std::assert, and provide no using declaration for assert.
- 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
- statement such as
- assert(word.size() > threshold);
- #The NDEBUG Preprocessor Variable
- 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.
- We can "turn off" debugging by providing a #define to define NDEBUG.
- 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:
- void print(const int ai[], size_t size)
- {
- #ifndef NDEBUG
- // _ _func_ _ is a local static defined by the compiler that holds the function's name
- cerr << _ _func _ _ << ": array size is " << size << endl;
- #endif
- // ..
- }
- 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.
- In addition to _ _func_ _, which the C++ compiler defines, the preprocessor defines four other names that can be useful in debugging:
- _ _FILE_ _ string literal containing the name of the file
- _ _LINE_ _ integer literal containing the current line number
- _ _TIME_ _ string literal containing the time the file was compiled
- _ _DATE_ _ string literal containing the date the file was compiled.
- We might use these constants to report additional information in error messages:
- if (word.size() < threshold)
- cerr << "Error: "<< _ _FILE_ _
- << " : in function " << _ _func_ _
- << " at line " << _ _LINE_ _ << endl
- << " Compiled on " << _ _DATE_ _
- << " at " << _ _TIME_ _ << endl
- << " Word read was \"" << word
- << "\": Length too short" << endl;
- If we give this program a string that is shorter than the threshold, then the following message will be generated:
- Error: wdebug.cc : in function main at line 27
- Compiled on Jul 11 2012 at 20:50:03
- Word read was "foo": Length too short
- #6.6.1 Argument Type Conversions
- 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:
- 1. An exact match. An exact match happens when:
- The argument and paramter types are identical.
- The argument is converted from an array or function type to the corresponding pointer type.
- A top-level const is added to or discarded from the argument.
- 2. Match through a const conversion. (4.11.2, p162)
- 3. Match through a promotion. (4.11.1, p160)
- 4. Match through an arithmetic ($4.11.1, p159) or pointer conversion (4.11.2, p161)
- 5. Match through a class-type conversion. (14.9, p579)
- #6.7 Pointers to Functions
- 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
- function's name is not part of its type. For Example:
- // compares lengths of two strings
- bool lengthCompare(const string &, const string &);
- 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
- // pf points to a function returning bool that takes two const string references
- bool (*pf)(const string &, const string &); // uninitialized
- 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
- points to a function that has two const string& paramters and returns bool.
- #Using Function Pointers
- 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:
- pf = lengthCompare; // pf now points to the function named lengthCompare
- pf = &lengthCompare; // equivalent assignment: address-of operator is optional
- 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:
- bool bq = pf("hello", "goodbye"); // calls lengthCompare
- bool b2 = (*pf)("hello", "goodbye"); // equivalent call
- bool b3 = lengthCompare("hello", "goodbye"); // equivalent call
- 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
- point to any function:
- string::size_type sumLength(const string&, const string&);
- bool cstrongCompare(const char*, const char*);
- pf = 0; // ok: pf points to no function
- pf = sumLength; // error: return type differs
- pf = cstringCompare; // error: parameter types differ
- pf = lengthCompare; // ok: function and pointer types match exactly
- #Pointers to Overloaded Functions
- 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
- void ff(int*);
- void ff(unsigned int);
- void (*pf1)(unsigned int) = ff; // pf1 points to ff(unsigned)
- 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:
- void (*pf2)(int) = ff; // error: no ff with a matching paramter list
- double (*pf3)(int*) = ff; // error: return type of ff and pf3 don't match
- #Function Pointer Parameters
- 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:
- // third paramter is a function type and is autmatically treated as a pointer to function
- void useBigger(const string &s1, const string &s2, bool pf(const string &, const string&));
- // equivalent declaration: explicitly define the parameter as a pointer to function
- void useBigger(const string &s1, const string &s2, bool (*pf)(const string &, const string &));
- When we pass a function as an argument, we can do so directly. It will be automatically converted to a pointer:
- // automatically converst thef unction lengthCompare to a pointer to function
- useBigger(s1, s2, lengthCompare);
- 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:
- typedef bool Func(const string&, const string&);
- typedef decltype(lengthCompare) Func2; // equivalent type
- // FuncP and FuncP2 have pointer to function type
- typedef bool(*FuncP)(const string&, const string&);
- typedef decltype(LengthCompare) *FuncP2; // equivalent type
- 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
- decltype returns a function type, if we want a pointer we must add the * ourselves. We can redeclare useBigger using any of these types:
- // equivalent declarations of useBigger using type aliases
- void useBigger(const string&, const string*, Func);
- void useBigger(const string&, const string*, FuncP2);
- Both declarations declare the same function. In the first case, the compiler will automatically convert the function type represented by Func to a pointer.
- #returning a pointer to function
- 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
- 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:
- using F = int(int*, int); // F is a function type, not a pointer
- using PF = int(*)(int*, int); // PF is a pointer type
- 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
- pointer type. We must explicitly specify that the return type is a pointer type:
- PF f1(int); // ok: PF is a pointer to function; f1 returns a pinter to function
- F f1(int); // error: F is a function type; f1 can't return a function
- F *f1(int); // ok: explicitly specify that the return type is a pointer to a function
- Of course, we can also declare f1 directly, which we'd do as
- int (*f1(int))(int*, int);
- 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
- function returns an int.
- For completeness, it's worth noting that we can simplify declarations of functions that return pointers to function by using a trailing return:
- auto f1(int) -> int (*)(int *, int);
- #Using auto or decltype for Function Pointer Types
- 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
- a third function that takes a string paramter and returns a pointer to one of these two functions as follows:
- string::size_type sumLength(const string&, const string&);
- string::size_type largerLength(const string&, const string&);
- // depending on the value of its string parmater, getFcn returns a pointer to sumLength or to largerLength
- deecltype(sumLength) *getFcn(const string &);
- 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