Use the De Morgan rule to understand the code.

Source: Internet
Author: User
Non-functional Code Determines the quality of the Code.
Use the De Morgan rule to understand the code Category: C ++ 53 reading Comment (0) Favorites Report

Today, I am reading code reading methods and practices. I found it interesting to use Morgan's law to analyze the code. I searched it online.

Bytes -----------------------------------------------------------------------------------------------------------------------

De Morgan rule:

    1. ! (X & Y) →! X |! Y
    2. ! (X | Y) →! X &&! Y

How can this be used?

For example, let's look at the code for finding the minimum value of a three-digit number:

  1. If (x <Y & x <z)
  2. Min = X;
  3. Else if (Y <z)
  4. Min = y;
  5. Else
  6. Min = z;

Many beginners (including me in the past) feel difficult to understand the above logic and always feel like nothing.

Let's take a look at the De Morgan rule,

The first if clause is used to judge x <Y & x <Z. If it is true, the minimum value is X. This is easy to understand. The key is to execute the following else if (Y <z) what are the conditions? Naturally

    1. ! (X <Y & x <z) → x> = Y | x> = z

So if you run this step, it means that X must be greater than Y and Z, so it must not be the minimum value, next, you just need to judge the size of Y and Z.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.