- Modern C++:Efficient and Scalable Application Development
- Richard Grimes Marius Bancila
- 286字
- 2021-06-10 18:27:51
Using constants and literals
Each type will have a literal representation. An integer will be a numeric represented without a decimal point and, if it is a signed integer, the literal can also use the plus or minus symbol to indicate the sign. Similarly, a real number can have a literal value that contains a decimal point, and you may even use the scientific (or engineering) format including an exponent. C++ has various rules to use when specifying literals in code. Some examples of literals are shown here:
int pos = +1;
int neg = -1;
double micro = 1e-6;
double unit = 1.;
std::string name = "Richard";
Note that for the unit variable, the compiler knows that the literal is a real number because the value has a decimal point. For integers, you can provide a hexadecimal literal in your code by prefixing the number with 0x, so 0x100 is 256 in decimal. By default, the output stream will print numeric values in base 10; however, you can insert a manipulator into an output stream to tell it to use a different number base. The default behavior is std::dec, which means the numbers should be displayed as base 10, std::oct means display as octal (base 8), and std::hex means display as hexadecimal (base 16). If you prefer to see the prefix printed, then you use the stream manipulator std::showbase (more details will be given in Chapter 5, Using the Standard Library Containers).
C++ defines some literals. For bool, the logic type, there are true and false constants, where false is zero and true is 1. There is also the nullptr constant, again, zero, which is used as an invalid value for any pointer type.