if (conditional) and ==, !=, <, > (comparison operators)
if
Condition description, combined with a comparison operator, is used to test whether a certain condition is true. For example, test whether an external input value is greater than a given number. if
The grammatical format of conditional narrative is as follows:.
1 2 3 4 |
|
The above program tests whether someVariable
is greater than 50. If it is true, the action written in the braces will be executed; in other words, if the statement in the braces is true, the code in the braces will be executed. Otherwise, if these codes are skipped and not executed, that is, this code has been omitted. .
If there is only one line of code to be executed after the condition is established, the braces can be omitted and not written.
1 2 3 4 5 6 7 8 9 10 11 |
|
The conditional formula in brackets should use the following operators:
Comparative operator:
x == y (x 等於 y)
x != y (x 不等於 y)
x < y (x 小於 y)
x > y (x 大於 y)
x <= y (x 小於等於 y)
x >= y (x 大於等於 y)
remind:
Be careful not to use the equal sign assign operator in the conditional expression incorrectly. For example: if (x = 10)
, this will assign x
to 10, rather than comparing whether x
and 10 are equal. .
Furthermore, if (x = 10)
Such a conditional statement will always be true. This is because the C language will execute this conditional statement as follows: first assign 10 to x
(remember that the single equal sign is the assign operator), and then evaluate if
statement to x
. Because the if
statement evaluates any non-zero value as TRUE, and at this time x
contains non-zero values, the conditional formula will always hold. This result makes the conditional judgment meaningless and not expected. In addition, this conditional statement assigns x
to 10, which is not a desired action. .
if
The description can also form part of the branch control structure, please refer to the description of if…else.
Grammar reference main page
This page is translated from the English version by Hot Blooded Youth LBU.
The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.