C++ Tip: Don't save lines of code

  • 2020-06-15 09:47:03
  • OfStack

This case comes from KDE4 source code.

Error code:


void LDAPProtocol::del( const KUrl &_url, bool )
{
 ....
 if ( (id = mOp.del( usrc.dn() ) == -1) ) {
  LDAPErr();
  return;
 }
 ret = mOp.waitForResult( id, -1 );
 ....
}

Description:

Some programmers go to great lengths to get more code down to one line. They are particularly keen on the "if" conditional statement, which completes assignments and comparisons once.

A typical error pattern is to use if (A = Foo() == Error) This expression right here. The example code we are working with above is exactly this error.

Comparison operations take precedence over assignment operations. That's why." mOp.del( usrc.dn() ) == -1 The comparison is performed first, and the value "true" (1) or "false" (0) is assigned to the variable id.

If mOp. del() returns "-1", the function terminates; Otherwise, the function keeps running and the "id" variable is given an incorrect value. It's always going to be equal to 0.

Correct code:


id = mOp.del(usrc.dn());
if ( id == -1 ) {

Advice:

Don't be lazy about writing extra code: complex expressions are hard to read, after all. Assign first, then compare. This will make it much easier for programmers to maintain your code in the future, and will reduce the possibility of errors.

Today's tip seems trivial, but I hope it will help you remember and force yourself to write clean, clean, and correct code instead of "Look how professional I am!" The style of

conclusion


Related articles: