Weird condition - sanity check, please?

Hi all,

I’m 95% sure this is something dumb that I’ve done, but I’ve been stuck for days. I should note that I haven’t written any C++ in about twenty years so the odds that this is a syntax issue are pretty high – I just cannot see it for the life of me.

With the disclaimer out of the way… here’s the problem code. I’ve boiled it down to the bare necessities to illustrate:

	#include "Serial.h"

ServicePortSerial sp;

bool flipped = true;

//----------------------------------------------------------------
// SETUP
//----------------------------------------------------------------

void setup() {
	sp.begin();
}


//----------------------------------------------------------------
// MAIN LOOP
//----------------------------------------------------------------

void loop() {
	byte foo;
	bool cond = true;

	sp.print("flipped: ");
	sp.println(flipped);

	if( !(flipped) ) {
		sp.println("I SHOULD NOT BE HERE");  // this does not execute
		foo = 99;  // this excecutes
	}

	sp.print("foo:");
	sp.println(foo);
}

For this setup, the console outputs:

flipped: 1
foo:99

What’s happening is that the setting of “foo” inside the if statement happens whether flipped is set or not BUT the print statement inside there does not fire. I would expect that the print statement doesn’t fire and “foo” remains set at zero.

If I change the code to check the value of the locally declared “cond” rather than “flipped” then it works as expected.

e.g.

    if( !cond ) {
	    sp.println("I SHOULD NOT BE HERE");
	    foo = 99; // this doesn't execute
    }

So the question boils down to:

  • The value of the local and the global are the same
  • I have traced out cond==flipped and it evaluates true
  • Why (this is the bit that is frying my noodle) does the assignment of foo execute but not the println?
  • did I do something overtly stupid or am I being screwed by the compiler?

thanks!
-O

This is an impressive case of bad luck. :slight_smile: GCC does not zero out local variables so “byte foo;” starts out with whatever value the memory address it is in had originally which happens to be… 99. :slight_smile:

Try changing it to “byte foo = 10;”.

3 Likes

Oh man thank you SO much! That was destroying my sanity!

1 Like