Avoiding / checking this very sinister source of errors in C ++

I recently came across an error as a result of a combination of typo, comma-operator, the default value. The term had many brackets and commas. One comma was placed in one bracket too far. This term was still valid C ++ code, but the return value was incorrect. In the simplified version, the error looked like this:

int intValue = MyString.toInt(),16; 

The toInt method has a default parameter for number-base (default is 10). The intValue variable will always be 16.

So the question is, is there any style rule to avoid such errors, or C ++ check / compile rules to help find such errors in the code?

EDIT

Ok, I modified the code a bit to make more sense for the comma:

 char * MyString("0x42"); int intValue = stringToInt(MyString),16; 

PS Please do not blame me for not using std :: string and streams. The code is for simplified demonstration only. :-)

+4
source share
2 answers

In GCC, -Wunused-value should give a warning in this case, since the return value of MyString.toInt() not used. This flag should help avoid most of these errors. To receive a warning, you may need to add the __attribute__ ((warn_unused_result)) attribute to the toInt method.

In any case, as shown, a simplified example leads to a compilation error "expected unqualified identification before a numeric constant" if parentheses are not added as follows: int intValue = (MyString.toInt(),16);

+5
source

What am I doing:

  • Readability and clarity are always in the first place. Do not combine a few simple expressions into a complex one. Instead, keep it simple . The fact that you are publishing simplified code, not the actual version, scares me. Anything too complicated to post here should not go in your code.
  • Do not use the default settings. I do not find them to add much importance to the readability that they subtract.
  • Do not use the comma operator .

In addition, do code reviews (the fact of the presence of a comma operator should have triggered a comment for review); unit test your code; and use statements to express assumptions and postconditions.

If you follow this advice just by reading your code after you type it , crooked lines will scream in your eyes.

+3
source

Source: https://habr.com/ru/post/1494914/


All Articles