2014
Nov
24
On compiler warnings (and off them, too)
Posted by David Zaslavsky on — EditedQuick, what’s wrong with this C++ program?
#include <iostream>
int test(int arg) {
cout << arg << endl;
}
int main(int argc, char** argv) {
test(5);
}
Did you guess nothing at all? Because that’s what GCC says:
$ g++ -o funnyprogram funnyprogram.cpp
$
WTF.
Pretty much every other programming language that makes you explicitly identify a function’s return type will also make you actually return something from that function. C and C++ don’t, and furthermore GCC doesn’t even warn you that anything is wrong. This can occasionally lead to serious bugs, as I discovered today in this real-world example. I had a function that checks the name of an object and returns an enum
value based on that name.
virtual const HardFactorOrder get_order() const {
// relies on a particular convention for get_name()
// but can be overridden for hard factors where that convention doesn't apply
std::string name = get_name();
if (name.compare(0, 3, "H01") == 0) {
return MIXED;
}
else if (name.compare(0, 2, "H0") == 0) {
return LO;
}
else if (name.compare(0, 2, "H1") == 0) {
return NLO;
}
};
That was all good when all the objects involved had names conforming to the convention, but my latest batch of updates to …