VectorLu

Essencial C++ Notes

The notes of Essential C++ —— the very book for the C++ beginners.

CH1 Basic C++ Programming

Define and Initialize a Data Object

Initialize

The data type determine the range of values the object can hold and the amount of the memory that must be allocated to hold the those values.

1
2
3
4
int userTries = 0;
// constructor syntax for template
int userRight(0);

% remainder oprerator

When might we actually use the remainder operator? Imagine that we want to print no more than eight strings on a line. If the number of words on the line is less than eight, we output a blank space following the word. If the string is the eighth word on the line, we output a newline. Here is our implementation:

1
2
3
4
const int lineSize = 8;
int cnt = 1;
cout << aString << (cnt % lineSize? ' ' : '\n');
cnt++;

Pointers Allow for Flexibility

To guard against dereferencing a null pointer, we test a pointer to see whether its address is zero.

1
2
3
if (pi && *pi != 1024) {
*pi = 1024;
}

The expression if (pi && ...) evaluates to true only if pi contains an address other than 0.

To test whether a pointer is null, we typically use the logical NOT operator:

1
if (!pi) // true if pi is set to 0

CH2 Procedural Programming

What should we do if the user requests an invalid position? The most extreme thing we can do is terminate the program. The standard libraty exit() function does just that. We pass it a value, and that value becomes the exit status of the program:

1
2
3
if (pos <= 0) {
exit(-1);
}

To use exit(), we must include the cstdlib header file:

1
#include <cstdlib>
您的支持将鼓励我继续创作!

热评文章