Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid/check this very sinister error-source in C++

Tags:

c++

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. :-)

like image 492
Valentin H Avatar asked Feb 16 '23 16:02

Valentin H


2 Answers

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);

like image 191
Joe Avatar answered Mar 03 '23 11:03

Joe


What I do is:

  • Readability and clarity always come first. Do not combine several simple expressions into a complex one. Instead, keep it simple. The fact that you post the simplified code, instead of the actual version, scares me. Anything that is too complex to post here should not go in your code.
  • Do not use default parameters. I don't find them to add much value for the readability they substract.
  • Do not use the comma operator.

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.

like image 22
Daniel Daranas Avatar answered Mar 03 '23 11:03

Daniel Daranas