vendredi 3 août 2018

I ran into a weird bug in c++ where an statement calculating an addition of 2 small integers overflow into a long long value

I recently ran into this weird C++ bug that I could not understand. Here's my code:

#include <bits/stdc++.h>
using namespace std;

typedef vector <int> vi;
typedef pair <int, int> ii;

#define ff first
#define ss second
#define pb push_back

const int N = 2050;

int n, k, sum = 0;
vector <ii> a;
vi pos;

int main (void) {
    cin >> n >> k;
    for (int i = 1; i < n+1; ++i) {
        int val;
        cin >> val;
        a.pb(ii(val, i));
    }

    cout << a.size()-1 << " " << k << " " << a.size()-k-1 << "\n";
}

When I tried out with test:

5 5
1 1 1 1 1

it returned:

4 5 4294967295

but when I changed the declaration from:

int n, k, sum = 0;

to:

long long n, k, sum = 0;

then the program returned the correct value which was:

4 5 -1

I could not figure out why the program behaved like that since -1 should not exceed an integer value. Can anyone explain this to me? I'm really appreciated your kind helps.

Thanks

Aucun commentaire:

Enregistrer un commentaire