recently I've stumbled on a bug as a result of the combination typo, comma-operator, default value. A term had a lot of parenthesis and commas. One comma was placed one parenthesis too far. The term was still a valid C++ code but the returned value was wrong. In simplified version the error looked like this:
int intValue = MyString.toInt(),16;
The method toInt
has a default parameter for number-base (default 10).
The variable intValue
would be always 16.
So the question is, is there any style-guide rule to avoid such bugs or a c++ checker/compiler rule to help finding such bugs in code?
EDIT
Ok, I've changed the code a little bit to make more sense for comma:
char * MyString("0x42");
int intValue = stringToInt(MyString),16;
P.S. Please don't blame me for not using std::string and streams. The code is only for simplified demonstration. :-)
With GCC, the -Wunused-value
should give a warning in this case, as the return value of MyString.toInt()
is not used. That flag should help avoid most such errors. To actually get the warning may require adding the __attribute__ ((warn_unused_result))
attribute to the toInt
method.
In any case, as shown the simplified example causes an "expected unqualified-id before numeric constant" compile error unless parentheses are added as follows int intValue = (MyString.toInt(),16);
What I do is:
Also, perform code reviews (the mere fact that a comma operator is present should have triggered a review comment); unit test your code; and use assertions to express preconditions and postconditions.
If you follow this advice, just reading your code after you type it will make erroneous lines scream at your eyes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With