Integer value redefined as int worked before edit, yet it shouldn't have. This is one of those "String" anomalies, isn't it?!

I realize that I didn’t need to use “int” here:
int wigValueI = wigValueS.toInt();

But even so, I cannot explain the following…
I decided to clean up the code and remove all the debug stuff when I stumbled on this. It seems my original code should never have worked. Why did it? Same results if Debug value true or false.

Defined at top before loop:


// other
int wigValueI = 0;
int wigSwitch = 0;

This was original code which works with correct value in wigValueI.


//find command in string (first 5 characters)
  String wigCommand = String (wigString.substring(0,5)) ;
 
//find value in string (next 3 characters after comma)
  String wigValueS = (wigString.substring(6,10));
                
// Check command start letter for D or A to prevent converting first character of value to a number
  if (wigCommand.charAt(0) != 'D' && wigCommand.charAt(0) != 'A') 
      if(DEBUG){Serial.print(">>Command Not D or A:");}
     int wigValueI = wigValueS.toInt();

since this doesn’t work… with zero in wigValueI


//find command in string (first 5 characters)
  String wigCommand = String (wigString.substring(0,5)) ;
 
//find value in string (next 3 characters after comma)
  String wigValueS = (wigString.substring(6,10));
                
// Check command start letter for D or A to prevent converting first character of value to a number
  if (wigCommand.charAt(0) != 'D' && wigCommand.charAt(0) != 'A') 
      int wigValueI = wigValueS.toInt();

And this works…with correct value in wigValueI (as I would expect)


//find command in string (first 5 characters)
  String wigCommand = String (wigString.substring(0,5)) ;
 
//find value in string (next 3 characters after comma)
  String wigValueS = (wigString.substring(6,10));
                
// Check command start letter for D or A to prevent converting first character of value to a number
  if (wigCommand.charAt(0) != 'D' && wigCommand.charAt(0) != 'A') 
      wigValueI = wigValueS.toInt();

To propperly answer this one, we’d need to see what the rest of your if(wigCommand...) actually looks like.
At the moment the statement hasn’t got a { ... } block, meaning that only the if(DEBUG) line was part of the condition and the int wigValueI = ... line had a scope beyond the if-condition.
When you removed that debug line, the next line became part of the if-condition-scope and hence the redeclared varilable wigValueI only lived inside that if-condition and was immediately removed after the semicolon again.

1 Like