Getting WA on your submission but can’t figure out why? There are many, many possibilities, but one (which crops up all the time) is Integer Overflow.
There’s a very simple way to see if your submission is triggering one of these: simply add
#pragma GCC optimize "trapv"
to the top of your submission, and instead of silently overflowing an int and giving a WA, your program will crash and give a RE.
For example, the only difference between this WA submission and this RE submission is the use of this pragma.
There’s tons of ways to detect silly mistakes in your code at both runtime and compile-time - have a look at this Codeforces article for more info! _GLIBCXX_DEBUG
in particular has helped me uncover tons of errors in other people’s code, though it doesn’t work with C-style arrays - which is yet another reason to use std::vector
instead _GLIBCXX_DEBUG
has a big performance impact, though, so make sure you remove it when you’ve finished debugging!
Edit:
Important update: unfortunately, there are cases where this doesn’t work: if a calculation’s result is too big to fit in an int
, but that calculation’s result is stored in a long long
and then assigned to an int
, then the error won’t be detected. Boo.
e.g.
[simon@simon-laptop][09:11:21]
[~/devel/hackerrank/otherpeoples]>cat ftrapv-count-example.cpp
#pragma GCC optimize "trapv"
#include <iostream>
using namespace std;
int main()
{
long long x;
cin >> x;
int tooSmallToStoreResultIfXIsMoreThan2 = 1'000'000'000;
// Equivalent to long long temporary = static_cast<long long>(tooSmallToStoreResultIfXIsMoreThan2) * x;
// tooSmallToStoreResultIfXIsMoreThan2 = temporary;
// This is an overflow, but -ftrapv does not detect it, alas.
tooSmallToStoreResultIfXIsMoreThan2 *= x;
cout << "x: " << x << " tooSmallToStoreResultIfXIsMoreThan2:" << tooSmallToStoreResultIfXIsMoreThan2 << endl;
}
[simon@simon-laptop][09:11:25]
[~/devel/hackerrank/otherpeoples]>g++ -std=c++17 ftrapv-count-example.cpp -I ../../shared -O3 -g3 -Wall
[simon@simon-laptop][09:11:30]
[~/devel/hackerrank/otherpeoples]>echo "3" | ./a.out
x: 3 tooSmallToStoreResultIfXIsMoreThan2:-1294967296