0
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
asked Apr 7, 2019 at 16:10
1
  • the 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 the if is ; (empty command) Commented Apr 7, 2019 at 17:09

1 Answer 1

3

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
5
  • 1
    Yeah, 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 for if (a=b). Valid, but bad practice.) Commented 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." Commented Apr 7, 2019 at 16:38
  • 1
    It should be on by default. Commented 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. :) Commented 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] Commented Apr 7, 2019 at 16:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.