What is an empty variable?

So if I did…

int x;

if(x == null)
or
if(x == “”)
or
Something else ???

1 Like

That depends entirely on whether int x; is a global variable (or more technically has “static storage duration”),
or a local variable (or more technically has “automatic storage duration”).

For a local variable, this is what we call “undefined behaviour” (or colloquially - “nasal demons”).
The variable is uninitialised, so it will be filled with a seemingly random value.

That value could be 0, it could be 4, it could be 42, you have no way of knowing, it will depend on which functions have been called before it was allocated.

For a global variable, it will be “zero initialised”, which unsurprisingly initialises it to 0.

2 Likes

This helps. I was having odd behavior and this makes sense why.

2 Likes

C++ was designed to produce optimal code,
and this is an example of one of those optimisation decisions - if the programmer doesn’t ask to initialise something, it won’t get initialised.

It’s actually quite rare to intentionally want to leave a variable uninitialised so in most cases you’ll want to explicitly initialise everything (though there are exceptional cases).

The compiler knows that using an uninitialised variable is bad,
so it will warn you about it if you turn all warnings on by going to File > Preferences and then setting warnings to ‘All’:

Unfortunately you will always get some warnings about EEPROM because the Arduino library designers did something daft when designing the EEPROM library, but having all warnings is useful because it can warn you about things you might not have noticed.