Comparison with 0 values:
1. Boolean variable vs. 0 value Comparison
Rule 1. You cannot compare Boolean variables directly with true, FALSE, or 1, 0.
Depending on the semantics of the Boolean type, the value of 0 is False (as false), and any non-0 value is True (it is recorded as true). The value of TRUE is exactly what does not have a uniform standard. For example, Visual C + + defines true as 1, while visual Basic defines true as-1.
Assuming that the Boolean variable is named flag, the standard if statement that compares it to the 0 value is as follows:
if (flag)//indicates that flag is true
if (!flag)//indicates flag is false
Other uses are bad styles, such as:
if (flag = = TRUE)
if (flag = = 1)
if (flag = = FALSE)
if (flag = = 0)
2. Integer variable vs. 0 value Comparison
Rule 1: You should use the integer variable with "= =" or "! = "Compare directly with 0.
Assuming that the integer variable is named value, the standard if statement that compares it to the 0 value is as follows:
if (value ==0)
if (value! = 0)
Cannot imitate the style of a Boolean variable and write it
if (value)//can make people misunderstand that value is a Boolean variable
if (!value)
3. Floating-point variable versus 0-value comparison
Rule 1: Do not use the floating-point variable "= =" or "! = "Compared to any number. Be aware that there is a precision limit for variables of either float or double type. So be sure to avoid using the floating-point variable "= =" or "! = "In comparison with numbers, you should try to convert them into" >= "or" <= "forms.
Assuming that the name of the floating-point variable is x, you should
if (x = = 0.0)//Comparison of implied errors
Translates to
if ((X>=-epsinon) && (X<=epsinon))
Where Epsinon is the allowable error (i.e. precision).
4. Pointer variable versus 0 value comparison
Rule 1: You should use the pointer variable "= =" or "! = "Compared to NULL. The 0 value of the pointer variable is "EMPTY" (marked as null). Although the value of NULL is the same as 0, the meaning of the two is different. Assuming that the pointer variable is named p, the standard if statement that compares to the 0 value is as follows:
if (p = = null)//p is explicitly compared with NULL, emphasizing that p is a pointer variable
if (P! = NULL)
Do not write
if (p = = 0)//easy to misunderstand p is an integer variable
if (P! = 0)
Or
if (p)//easy to misunderstand P is a Boolean variable
if (!p)
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Comparison with 0 values