Unused variable when it is used as the return value [Solved]

Thread Starter

AlbertHall

Joined Jun 4, 2014
9,331
[Arduino]
The function below generates a warning "warning: variable 'OK' set but not used ". It is only a warning but I would like to understand why, and to eliminate the warning if possible.
Code:
bool HC12SetBaud(enum HC12Baud Baud)
{
  uint16_t BaudRate;
  char BaudCommand[11];
  bool OK = false;
   
  switch(Baud)
  {
    case Baud1200:
      BaudRate = 1200;
      break;
    case Baud2400:
      BaudRate = 2400;
      break;
    case Baud4800:
      BaudRate = 4800;
      break;
    case Baud9600:
      BaudRate = 9600;
      break;
    case Baud19200:
      BaudRate = 19200;
      break;
    case Baud38400:
      BaudRate = 38400;
      break;
    case Baud57600:
      BaudRate = 57600;
      break;
    default:
      BaudRate = 0;
  }
  if(BaudRate >0)
  {
    sprintf(BaudCommand, "AT+B%u%c", BaudRate,'\n');
    Serial.print(BaudCommand);
    OK = SendLocal(BaudCommand);
    //SwSerial.end;
    SwSerial.begin(BaudRate);   
  }
  return OK;
}
 
Last edited:

BobaMosfet

Joined Jul 1, 2009
1,012
[Arduino]
The function below generates a warning "warning: variable 'OK' set but not used ". It is only a warning but I would like to understand why, and to eliminate the warning if possible.
Code:
bool HC12SetBaud(enum HC12Baud Baud)
{
  uint16_t BaudRate;
  char BaudCommand[11];
  bool OK = false;
  
  switch(Baud)
  {
    case Baud1200:
      BaudRate = 1200;
      break;
    case Baud2400:
      BaudRate = 2400;
      break;
    case Baud4800:
      BaudRate = 4800;
      break;
    case Baud9600:
      BaudRate = 9600;
      break;
    case Baud19200:
      BaudRate = 19200;
      break;
    case Baud38400:
      BaudRate = 38400;
      break;
    case Baud57600:
      BaudRate = 57600;
      break;
    default:
      BaudRate = 0;
  }
  if(BaudRate >0)
  {
    sprintf(BaudCommand, "AT+B%u%c", BaudRate,'\n');
    Serial.print(BaudCommand);
    OK = SendLocal(BaudCommand);
    //SwSerial.end;
    SwSerial.begin(BaudRate);  
  }
  return OK;
}
You can always explicitly set OK.

Code:
bool  OK;

OK = false;
 

BobaMosfet

Joined Jul 1, 2009
1,012
Does that produce a result different to line 5 of the original code?
It shouldn't because in both cases the representation of 'false' (whatever it is defined to be) is placed into the memory location, in the stack-frame- and in both cases it takes 1 or more mnemonics to do it. It's a stack frame. mnemonics are required to create space on the stackframe for a variable of that size- which remains uninitialized (whatever value is in memory where it happens to be is what it is). Then when you tell the compiler to set it to 'false', it uses additional mnemonics to change that memory value to whatever the compiler deems 'false' is defined or typdef'd as. Compiler treatment and optimization may vary.
 
Last edited:
Top