0

I have a small program that defines a type in types.h

typedef int ErrorCode;

In another file global.c I include that file

#include "types.h"

const ErrorCode NEW_NETWORK_ERROR      = -1;
const ErrorCode NO_ERROR               = 0;
const ErrorCode TOO_MANY_NODES_ERROR   = 1;
...

and have a small function that takes an ErrorCode and runs a switch statement on said integer.

void stringify(ErrorCode ec, char* buffer, int bufferSize) {
  switch(ec) {
  case NO_ERROR:
    strncpy(buffer, "THIS IS NOT AN ERROR ERROR", bufferSize);
    break;
  case TOO_MANY_NODES_ERROR:
    strncpy(buffer, "TOO_MANY_NODES_ERROR", bufferSize);
    break;

/* redacted cases for brevity */
  default:
    strncpy(buffer, "No string for error supplied.", bufferSize);
  }
}

When compiling this with -O1 or -O2 it works just fine but as soon as I try to use -O0 it throws an error on this file.


..\global.c: In function 'stringify':
..\global.c:143:3: error: case label does not reduce to an integer constant
   case NO_ERROR:
   ^~~~
and so on for every case label.

I have tried to remove every known warning flag in eclipse c/c++ IDE.

It is a c program, compiling using MingW x86_64-w64-mingw32

version : MinGW-W64-builds-4.3.5 under the eclipse IDE.

Nothing works except use of optimization, is this a known problem, because I expected that typedef'd ints would reduce just fine for case labels in a switch statement regardless of what optimization level I compile with.

Erik
  • 101
  • 5
  • 2
    `const int something` is not a constant expression in C language required in the `case` statement – 0___________ Aug 02 '23 at 13:17
  • ... so use a macro or an `enum` constant instead if you want to symbols instead of raw numbers. – John Bollinger Aug 02 '23 at 13:27
  • I was aware that const isn't really a constant, I am just surprised that no optimization would make a difference. But thinking about it it makes kind of sense, in a backwards kind of badly defined const keyword way – Erik Aug 02 '23 at 19:13

0 Answers0