Empty Particle.variable can't be read

Why does the code below return error when reading the variable in Particle App and Console ? If message is empty or a single space, it fails. If it has a value or is two spaces, it succeeds. I have reduced the code to the bare minimum for clarity. You will have to fix the double quotes.

char* message = "";
void setup() {
void loop() {

I just tried this out of curiosity. I get the same issue.
But I get a warning when I build the project, so it could be that the issue is there (and not on the Particle Cloud):

warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
  253 | char *message = "";
      |                 ^~

is an acceptable work around a . (dot) or a space as the value?

EDIT: Another option could be:


I’m not sure what is going on, but it also got me curious. From what I could scoop from the .variable() code you might be better off by using NULL or nullptr as initialization value. That might fix your original problem and also address the fact that char *message is not your string but in fact your pointer to a future string

You could also use char[SOME_SIZE] or Particle’s String

Unlike a char[] a char* is inherently “movable” only the pointer is at a given place but not the string itself but that is required for Particle.variable().

When doing it as you did there is no point in having the pointer as non-const as it wouldn’t be safe to store a string in that location since there only one character “allocated” not a string of arbitrary length…

char* should only be used when you explicitly want a “movable” pointer.
const char* is useful for immutable strings.
For “mutating” strings I’d always use char[SOMESIZE] where SOMESIZE is chosen appropriately for the longes expected string.

BTW, with a global char* message = ""; you may even have the optimizer do away with the “string” entirely as a “movable” pointer to '\0' is of no value to anybody and hence there is little use in instantiating it in the first place.

I’d have to double check but I don’t think that’ll work either.
AFAICT not the poiner variable is stored but only the address the pointer is pointing to at the time Particle.variable() is registered.
I wouldn’t expect that the `Particle.variable() would follow a subsequent redirection of the pointer to a new string.

However, the fact that a correctly setup variable holding an empty string causes the request to fail with {"ok":false,"error":"Unknown Variable: msg"} seems a bug to me - @m_m?


I just looked it up again. You are 100% right as char* and variations go. It only registers the address pointed to, no the pointers address (variable address). Good catch!

Other types such as int, double, and String do have the variable address registered and that’s where I got the wrong idea for char*

1 Like