Difference between two stack size (using size()) in std::cout

Viewed 51

I am confused why the two print statements give different output. Attaching the code snippet below. Any help would be appreciated. Thank You.

    stack<int>st1;
    stack<int>st2;
    
    st2.push(222);
    
    cout<<"st1 size:"<<st1.size()<<endl;
    cout<<"st2 size:"<<st2.size()<<endl;
    
    int a=st1.size();
    int b=st2.size();
    cout<<"difference:"<<a-b<<endl;
    cout<<"difference:"<<(st1.size()-st2.size())<<endl; //why this is giving different ans
    /* output:
        st1 size:0
        st2 size:1
        difference:-1
        difference:4294967295
     */
2 Answers

Take a look at the return type of the member function size. I bet that you'll find it is an unsigned type.

What happens when you calculate 0u - 1 with unsigned integers? The result cannot be -1 because that number isn't representable by an unsigned type. The result will be a positive number that is congruent with -1 modulo the number of representable values. Which is also the largest value representable by that unsigned type.

It is because int is a signed type while std::stack::size() returns an unsigned value.

Calculation of unsigned integer wraps around when the result is going to out of the range of value that can be represented by the type.

Related