Question

I have the warnings from the gcc compiler showing the const char issue.

How to get rid of the warnings?

Thanks, Michael

char * str_convert(int op) {
  /*returns the string corresponding to an operation opcode. Used for screen output.*/
  if(op == PLUS) {
    return "plus";
  }
  else if (op == MULT) {
    return "mult";
  }
  else if (op == SUBS) {
    return "subs";
  }
  else if (op == MOD) {
    return "mod";
  }
  else if (op == ABS) {
    return "abs";
  }
  else if (op == MAX) {
    return "max";
  }
  else if (op == MIN) {
    return "min";
  }
  else {
    return NULL;
  }
}
Was it helpful?

Solution

I think the fix is adding const to the return type (to prevent modification of the contents). I'd also change the if cascade to switch / case, but that's unrelated to the problem.

const char * str_convert(int op) {
  /*returns the string corresponding to an operation opcode. Used for screen output.*/
  switch (op) {
    case ABS:  return "abs";
    case MAX:  return "max";
    case MIN:  return "min";
    case MOD:  return "mod";
    case MULT: return "mult";
    case PLUS: return "plus";
    case SUBS: return "subs";
    default: return NULL;
  }
}

OTHER TIPS

You may also wish to consider using templated 'op' value as the compiler will replace the jump table it will use for the the switch statement implementation, evaluated at runtime, with a compile time evaluated version that calls on of N functions, depending on the template value.

template <int op>
const char * str_convert(void) 
{
    /*returns the string corresponding to an operation opcode. Used for screen output.*/
    switch (op) 
    {
        case ABS:  return "abs";
        case MAX:  return "max";
        case MIN:  return "min";
        case MOD:  return "mod";
        case MULT: return "mult";
        case PLUS: return "plus";
        case SUBS: return "subs";
        default: return NULL;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top