The C++14 standard provides two new small features to the language: binary literals and digit separators. They are already available in Clang 3.4 and GCC 4.9 and now Visual Studio 2015 RC has implemented them. They may not be something you can’t live without, but sometimes it’s convenient to have them. Let’s have a look.
In C++ it was possible to input integer literals in several bases: decimal, hexadecimal and octal. However, the binary base has been omitted (though other languages supported that). With C++14 binary is also supported and binary literals are introduced with the prefix 0b or 0B.
1 2 3 4 |
int i1 = 42; int i2 = 052; int i3 = 0x2A; int i4 = 0b101010; |
Binary literals can be used anywhere integral literals are expected.
1 2 3 4 5 6 |
enum class flags { read = 0b0001, write = 0b0010, execute = 0b0100 }; |
What if you had to write large literals such as 0b101111000110000101001110, which is the binary representation of decimal 12345678? Sometimes it is convenient to separate groups of digits for more human readability.
C++14 defines the single quotation mark (') as a digit separator in integral and floating point literals. So the binary literal 0b101111000110000101001110 can be expressed in several ways:
1 2 |
int n1 = 0b1011'1100'0110'0001'0100'1110; int n2 = 0b10111100'01100001'01001110; |
or maybe in hexadecimal:
1 |
int n3 = 0xbc'61'4e; |
The position of the single quotation marks in the integral or floating point literals is irrelevant, they are simply ignored when determining the value of the literal. All the following are equivalent (but probably only the first and the last make sense).
1 2 3 4 5 6 |
int n1 = 12345; int n2 = 1'2'3'4'5; int n3 = 1'23'4'5; int n4 = 1'234'5; int n5 = 12'3'45; int n6 = 12'345; |