x = 5;
Serial.println (x);
if (x == 0);
{
//stuff in this IF keeps happening why ?
//Iam too stupid ?
}
Duncan C
5,7523 gold badges19 silver badges30 bronze badges
1 Answer 1
You have a rogue semi-colon.
Splitting your code up on the end of statements you get:
1. x = 5;
2. Serial.println (x);
3. if (x == 0);
4. { // stuff }
With the semi-colon after the if
it terminates the if
before the opening block {
, and that block becomes a completely separate statement detached from the if
.
answered Apr 7, 2019 at 16:16
-
1Yeah, most of us have been bitten by this one. I wish C/C++ compilers would flag this
if (condition);
form with a warning as it is very likely a mistake, and is certainly bad coding practice even if intentional. (Same forif (a=b)
. Valid, but bad practice.)Duncan C– Duncan C2019年04月07日 16:37:13 +00:00Commented Apr 7, 2019 at 16:37 -
1@DuncanC They can. GCC has the flag
-Wempty-body
: "Warn if an empty body occurs in an "if", "else" or "do while" statement. This warning is also enabled by -Wextra."Majenko– Majenko2019年04月07日 16:38:23 +00:00Commented Apr 7, 2019 at 16:38 -
1It should be on by default.Duncan C– Duncan C2019年04月07日 16:41:42 +00:00Commented Apr 7, 2019 at 16:41
-
Hell, I'd even argue it should be flagged as an error. Anybody who deliberately writes a "side-effect only"
if
statement should be shot. :)Duncan C– Duncan C2019年04月07日 16:42:10 +00:00Commented Apr 7, 2019 at 16:42 -
You can turn it on in preferences in the Aduino IDE.
/home/matt/Arduino/sketch_mar30a/sketch_mar30a.ino:5:14: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
Majenko– Majenko2019年04月07日 16:43:07 +00:00Commented Apr 7, 2019 at 16:43
Explore related questions
See similar questions with these tags.
lang-cpp
if
statement must be executed to evaluate the condition. if the condition is true the following command or block of commands is executed. your command after theif
is;
(empty command)