"if" isn't working

IDE 2.2.1

bool debug = 0;

void setup() {  //setup()
  Serial.begin(9600);
}  //setup()

void loop() {  //loop()

if (debug = 1) { //debug
    Serial.println("EthernetUDP_test1.ino");
    Serial.println();
  } //debug

} //loop()

"if" is not capitalized in the reference library, so I tried it that way. The file as shown compiles and downloads to my Uno. The results are;

EthernetUDP_test1.ino

EthernetUDP_test1.ino

EthernetUDP_test1.ino......

"debug" shows false, yet the script runs as if "debug" was true.
I'm obviously doing something wrong. What is it?

try

if(debug==1)
2 Likes

Exactly,
The reason for that is if you use

if(debug=1)

You are setting debug to 1
If you use:

if(debug==1)

You are checking if it equals one or not

1 Like

Exactly.

and the value of the expression within the if() is also 1 - so the if() will always see that as true.

1 Like

Duh.
Thank you.

1 Like

Good development tools will warn you about mistakes like this. Before such tools were commonly available it was good practice to write the if statement like

if (1 == debug)
{
}

That way if you mistakenly typed "=" instead of "==" it would fail to compile and be an obvious error.

2 Likes

Do you have any suggestions for better development tools?

Better dev tools?
Like IDEs?

For a beginner you could try and use the autocomplete in Arduino IDE 2.x.x
Eclipse IDE?

One thing you must do is to go to the preferences pane in the IDE and crank up all compiler messages and verbosity.

Then you will get warnings about some things like this one that hung you up for a bit.

Heed the red ink, and if it is talking about your code, fix your code until there are no warnings.

HTH

a7

2 Likes

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.