Friday 10 April 2009

Assignment FAIL!

One of the things I've been having to do lately is make sure that my C++ complies with high integrity C++ rules and guidelines (HICPP) which though interesting has been a massive pain as I've gotten use to doing things in a certain way and now I have to double-check everything I write for compliance. One which takes more getting use to than most is the use of the comparison operator in control statements, normally I (along with most people I think) would do a check something along the lines of "if my value is equal to three then...", or

int x = 3;
if (x == 3) { ... }


Now this is invalid in HICPP because a programmer could accidentally type "if (x = 3)" which of course is assignment instead of comparison, so the rule states that instead the comparison should be written as

int x = 3;
if (3 == x) { ... }


The reason for this is that the former is perfectly valid C++ syntax and will compile and run (but not work), whereas the latter will cause a compiler error because you cannot assign a value to a literal value.

This is one of a few rules which I am likely to carry into my every day coding as it helps to prevent me from making stupid mistakes which as a human I am more than capable of making. Another one which takes only a little more effort but can save until problems is when looping over a collection, the rules state that instead of doing this...

vector values;
// Add values to collection

for (int i = 0; i < values.size(); i++) { ... }


It should be written as...

vector values;
// Add values to collection

int size = values.size()
for (int i = 0; i < size; i++) { ... }


Which again makes sense as with the latter method you avoid problems if the length of your collection changes. Of course this doesn't work so well if the loop is suppose to change the size of the collection, but that's a reasonable exception.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.