SoFunction
Updated on 2025-03-09

C++ tips: Don't save the number of lines of code

This case comes from the KDE4 source code.

Error code:

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

illustrate:

Some programmers try their best to squeeze more code into one line. They are particularly keen on the "if" conditional statement, and complete assignment and comparison at one time.

A typical error pattern is to useif (A = Foo() == Error) Such an expression. The example code we are dealing with above is exactly this error.

The priority of the comparison operation is higher than the assignment operation. that's why"( () ) == -1″ The comparison is performed first, and then the "true"(1) or "false"(0) value is assigned to the variable id.

If () returns "-1", the function will terminate; otherwise, the function will continue to run and the "id" variable will be assigned an incorrect value. Its result is always 0.

Correct code:

id = (());
if ( id == -1 ) {

suggestion:

Don't bother writing extra code: after all, complex expressions are difficult to understand. First, assign values ​​and then compare. In this way, the programmers who maintain your code will be much easier in the future and will reduce the possibility of errors.

This little trick today looks trivial, but I hope it will help you, keep in mind and force yourself to write clean and tidy code instead of the “see how professional I am!” style

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the following links