문제

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;
  }
}
도움이 되었습니까?

해결책

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;
  }
}

다른 팁

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;
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top