Problem with variable declaration

Hey there,

i have a problem with a variable that would not available outside from if{}. I've never seen this before.

String print_state = "-";

void test(topic, json) {
  ...
   doing json stuff
  ...

  if (String(topic) == "octoprint/progress/printing"){
    String print_state = parsed["progress"];
    Serial.println("State " + print_state);
  } 
  Serial.println("State " + print_state);
}

This is the Script and i send 10 to the function this the output:

State 10
State -

So, i send a json sting with some data. The string gets read and the data is there, but only in the if{}. I don't know, why my variable "print_state" is not available in the complete function.

Hope someone can help me.

You are re-declaring “print_state” as a local variable in your “if” statement. Remove the preceeding “String” from “print_state” in the “if” block and you’re good.

And another note: Do not use the String class at all :slight_smile:

If you define a variable within an IF statement it no longer exists when the IF statement completes.

I wonder if you are unintentionally creating a local variable with the same name as a global variable. When you prefix a variable name with String (or char or int) it tells the compiler to create a new variable. If you just want to use an existing variable don't use the prefix.

Alternatively, create the variable before the IF statement.

Separately ... It is not a good idea to use the String (capital S) class on an Arduino as it can cause memory corruption in the small memory on an Arduino. Just use cstrings - char arrays terminated with 0.

...R

Thanks a lot for your hints guys. I didn't know that i can declare local variables in IF statements. I've never seen this in other languages.

I'm not good in C programming, i do it only for a few little IOT things at home.

So, with your hits it works now. Thanks :)

I didn't know that i can declare local variables in IF statements. I've never seen this in other languages.

You can define variables just about anywhere in C++, but their scope will be limited to the particular code block they are defined in.

It is a common feature of most high-level language.