Null Type

Why can't I do something as simple as:

String test;

void setup()
{
  test = null;

  if(test != null)
  {
    //Do stuff here
  }
  else
  {
    //Do more stuff here
  }
}

void loop()
{

}

Specifically I'm trying to do this in .h and .cpp files, however, no difference. Doesn't work there, or in the main Arduino file. C++ was my first language and C# is my fluent language. I'm pretty sure I'm doing it right, but is there something I've forgotten? Can't find it in search either.

Thanks,
Stauffski

1 Like

In C/C++, the keyword is NULL, not null. Case makes a difference.

2 Likes

Ahhhh. The Arduino syntax coloring threw me off. "null" turned orange, never crossed my mind that it could be wrong.

Thanks.

Assigning NULL to the string probably isn't quite having the effect you might be imagining. The String class isn't a pointer (or derived from one). NULL is really defined as 0, so you are really assigning and comparing zero, and calling it NULL is just confusing.

See this test, based on yours:

String test;

void setup()
{
  Serial.begin (115200);

  test = NULL;

  if(test != NULL)
  {
    Serial.println ("not equal to NULL");
  }
  else
  {
    Serial.println ("is equal to NULL");
    Serial.println (test);

    if (test == "0")
      Serial.println ("is equal to zero");
  }
}

void loop() {}

This prints:

is equal to NULL
0
is equal to zero

Certainly this isn't the same as "the empty string" or "no string". It's just a zero.