Strange behaviour of long long

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define testcase  \
    ll tc, t = 1; \
    cin >> tc;    \
    while (tc--)
#define fast                      \
    ios_base::sync_with_stdio(0); \
    cin.tie(0);
#define vll vector<ll>
int main()
{
    long long n = 0, m = 0, i = 0, j = 0, k = 0, l = 0, x = 0, y = 0;
    string a, b;
    cin >> n >> a >> b;
    vector<long long> c0, c1;
    for (i = 0; i < n; i++)
    {
        if (a[i] != b[i])
        {
            if (a[i] == '0')
                c0.push_back(i);
            else
                c1.push_back(i);
        }
    }
    k = c1.size() - c0.size();
    ll ans = abs(k);
    cout << c0.size() << " " << c1.size() << " " << k << "\n";
    return 0;
}

tc.:
        8
        10001001
        01101110
output
       4 2 4294967294

when c0.size is 4 and c1.size is 2 then why k(c1.size() - c0.size()) stores 4294967294

1 Like


it gives expected answer :thinking:

actually I use gcc g++ 6.4.0 in cf i am getting this and also in my ide i am getting same

This is because the value returned by XYZ.size() is unsigned (in this case unsigned long long) and when you do (c1.size()-c0.size()) it has value (2-4) so result is expected to be -2 but since both the operands with subtraction are unsigned long long so the result is also evaluated as unsigned long long. So how -2 is represented in unsigned long long? there are no negative numbers in unsigned long long, but it overflow so you get wrong result so before subtracting try to type cast in long long before subtracting to get correct result

1 Like

Screenshot from 2021-02-04 11-01-46
I am getting this output in my local machine too. @ssjgz may help.

Both of you try adding:

    cout << "sizeof (long long): " << sizeof(long long) << " sizeof vector:size_type: "  << sizeof(vector<long long>::size_type) << std::endl;

I bet @phoenixsoul will get:

sizeof (long long): 8 sizeof vector:size_type: 4

and @suman_18733097 will get:

sizeof (long long): 8 sizeof vector:size_type: 8
2 Likes

bro check the output very carefully …it shows in my case is 4 2 -2.which is absolitely true.

yeah you are true why is that we both got different output…

thanks alot… i understand now

1 Like

32-bit vs 64-bit is the most likely cause of the differences in the sizeof.

2 Likes

ohh i see now…
btw thanks i learnt new things

1 Like