Hello. Studying the book of Bjarne Stroustrup, I came across an interesting, in my opinion, example:

class Tiny { char v; void assign(int i) { if(i&~077) // #1 throw Bad_range(); v = i; } public: class Bad_range{}; Tiny(int i) { assign(i); } Tiny& operator = (int i) { assign(i); return *this; } operator int() const { return v; } }; int main () { Tiny c1 = 2; Tiny c2 = 1; Tiny c3 = c1 - c2; // #2 } 

So, the first question (# 1), what is this condition, since I see it for the first time. And (# 2), the expression ( c1 - c2 ) will turn into int or Tiny ? And will there be a difference in performance, if you do not take into account the second question?

  • one
    for two different questions (unrelated) it is better to create two separate questions on StackOverflow. And your questions as far as I can see do not depend on each other. - Mikhail Rebrov

1 answer 1

077 - the number in the octal number system, which is written in binary as 00..00111111 - zeros to the size of int . The operation ~ reverses all bits, i.e. it turns out 11..11000000. The operation of bitwise AND with such a number gives true (non-zero value) if there is at least one single bit in the number starting with 6 (counting from zero). So this is a test that a number from 0 to 63 inclusive (both for unsigned and signed numbers), or rather, a number outside this range - then an exception is generated.

In the second part, c1 and c2 for the difference will be cast to the type int (operator int() ), and the result of subtracting the type int will be used to create an object c3 type Tiny (constructor Tiny(int) ).