Today I wanted to write a small function to render integers up to 64bit in binary. There I ran across a problem which is apparently due to silent integer promotion. Below source code shows the problem.
#include <iostream>
#include <string>
using namespace std;
string pretty(uint64_t);
string pretty_correct(uint64_t);
string pretty(uint64_t var)
{
string result;
result.reserve(50);
for ( short i=63; i>=0; --i ) {
if ( var & (0x1 << i) )
result.append(1,'|');
else
result.append(1,'O');
}
return result;
}
string pretty_correct(uint64_t var)
{
string result;
result.reserve(50);
for ( short i=63; i>=0; --i ) {
if ( var & (static_cast<unsigned short>(0x1 << i)))
result.append(1,'|');
else
result.append(1,'O');
}
return result;
}
int main() {
cout << pretty(12345678901234567890U) << " <- wrong!"<< endl;
cout << pretty_correct(12345678901234567890U) << " <- right!"<< endl;
}
I am looking for a way for GCC (or maybe Clang) to spit out a warning for this type of problem. All solutions that were presented to me so far involved me somehow presciently being aware that this kind of problem might occur. But the way this occurs now it might introduce subtle bugs into my code, which would be difficult to track down.
Edit: These are the commands I'm using for compilation:
g++ -std=c++14 -Wall -Wextra -pedantic-errors -Wconversion -g -o testcase testcase.cpp
clang -std=c++14 -Weverything -g -o testcase testcase.cpp -lm -lstdc++