Why did this compile OK and what did it do?

I"m using Arduino IDE 1.8.9, Compiler warning: None

I mistakenly coded

    if (Snerd) {
       ....
    }

int Snerd() {
  // do stuff and return true or false
}

and the code compiled OK and the code within the IF never executed.

This probably would have thrown a warning or error if I had my preferences set accordingly but it compiled and ran. When it ran it apparently took 'if (Snerd)' as false. Obviously I should have coded 'if (Snerd())' and I eventually caught this mistake.

But if I had coded

  if (notdefined)  {
    ...
  }

The compiler would have (and does) flag it as an error.

Any idea what the compiler thought it was doing when it let my original code compile and run?

Snerd is a pointer to the function so the name is defined and so if (Snerd) {... will test if that pointer is not null.

Because the function exists (the pointer points somewhere) the content of the if should be executed

try this code

bool Snerd() {
  return random(100) > 42;
}

void setup() {
  Serial.begin(115200);
  if (Snerd) {
    Serial.println("The Snerd function pointer is not null");
  } else {
    Serial.println("The Snerd function pointer is null");
  }
}

void loop() {}

I'm willing to bet that you'll see The Snerd function pointer is not null in the serial monitor

1 Like

the code within the IF never executed.

Check again.

This compiles on Arduino 1.8.19

void setup() {
  if (loop) {
  }
}

void loop() {}

with the warning:

C:\Users\Jim\Desktop\Clue\sketch_apr11a\sketch_apr11a.ino: In function 'void setup()':
C:\Users\Jim\Desktop\Clue\sketch_apr11a\sketch_apr11a.ino:3:8: warning: the address of 'void loop()' will never be NULL [-Waddress]
 if(loop) {
        ^
1 Like

Ahh, That makes sense.

It makes even more sense since after I changed my preference to Compiler Warning: Default, it still didn't flag it as an error. Now I understand that it isn't an error (at least as the compiler sees things).

Thank you.

In practice the optimiser gets rid of the if test altogether since the test is always true :slight_smile:
so the code

bool Snerd() {
  return random(100) > 42;
}

void setup() {
  Serial.begin(115200);
  if (Snerd) {
    Serial.println("The Snerd function pointer is not null");
  } else {
    Serial.println("The Snerd function pointer is null");
  }
}

void loop() {}

is probably compiled as if you had written

void setup() {
  Serial.begin(115200);
  Serial.println("The Snerd function pointer is not null");
}

void loop() {}

the rest is removed as the function is never called

Humans see it the same way as the compiler, which is only following the rules humans set. The warning is useful to catch typos.

It is important to be able to check if a function pointer is not NULL, in which case the if statement can be extremely useful.

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