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...
vectorvalues;
// Add values to collection
for (int i = 0; i < values.size(); i++) { ... }
It should be written as...
vectorvalues;
// 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.