Variable set inside IF statement is NULL or nothing outside IF ???

Hi guys

I'm setting a string variable (String recipient) inside an if statement. Problem is, I'm trying to use that variable outside the IF statement. I'm new to the arduino but normally I wouldn't consider this to be a problem.

But when I try to print the variable outside the IF statement, it's set to "nothing". Doesn't make sense to me - why wouldn't a variable survive outside an IF statement?

String recipient is declared as a global variable. I'm running the arduino code on an ESP8266 if that's relevant to know.

I hope some of you clever guys can spot my mistake?
Thanks in advance.

Cheers :slight_smile:

  Serial.print("Recipient 1: ");
  Serial.println(Settings.cpsms_receiver1); // Outputs int e.g. 4500000000

  Serial.print("Recipient 2: ");
  Serial.println(Settings.cpsms_receiver2); // Outputs int e.g. 4500000000
  
  if ( Settings.cpsms_receiver1 != NULL ) {
    String recipient = String(Settings.cpsms_receiver1);
    Serial.println("Recipient 1: OK"); // This is printed
  }
  
  if (( Settings.cpsms_receiver1 != NULL ) && ( Settings.cpsms_receiver2 != NULL )) {
    String recipient = String(Settings.cpsms_receiver1 + "," + Settings.cpsms_receiver2);
    Serial.println("Recipient 2: OK"); // This is printed if 2 recipients are set
  }

  Serial.print("Recipients: ");
  Serial.println(recipient); // Outputs nothing ? Why ???

You need to understand the scope of a variable.

A variable only exists with the block in which it is defined. A block is code between { and }, or global if defined outside of all blocks.

But I'm declaring the variable recipient as a global variable. Shouldn't that be enough?

Hello,

The problem is that you are not using the global variable, instead you declare a new, local variable. So this:

Serial.println(recipient); // Outputs nothing ? Why ???

will use the global variable, not the local ones, which are not accessible in this part of your code.

To fix it, simply remove the "String" in front of the variable name in your IF's, then it will use the global variable.

Ahh... I understand.
Thanks! :slight_smile:

Rookie mistake :smiley:

As you provided snippets, hard to tell exactly what you are doing.

String recipient = String(Settings.cpsms_receiver1);

This declares a variable, as per guix post. If you have a global of the same name the local name overrides the global. Bad practice to use the same name for this reason.

marco_c:
As you provided snippets, hard to tell exactly what you are doing.

String recipient = String(Settings.cpsms_receiver1);

This declares a variable, as per guix post. If you have a global of the same name the local name overrides the global. Bad practice to use the same name for this reason.

I understand - I wasn't trying to declare the variable twice, but only to set it's value inside the IF statement.
As I said, rookie mistake :smiley: