https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78731
Bug ID: 78731 Summary: Possible bug with switch when optimization is turned on. Product: gcc Version: 5.4.1 Status: UNCONFIRMED Severity: normal Priority: P3 Component: tree-optimization Assignee: unassigned at gcc dot gnu.org Reporter: wilson at gcc dot gnu.org Target Milestone: --- Creating a bug from the original message, which is here https://gcc.gnu.org/ml/gcc-bugs/2016-12/msg00678.html Hi The following code seems to be correctly executed when compiled with GCC 4.4.7 and LLVM 6.1. It does not correctly compile with gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.4). The following is what I have reduced the problem to: #include <stdio.h> #include <stdlib.h> #define GENERAL 1 #define BRACKETS 2 #define QUOTES 3 //This method contains the issue. void foo(char *qb, char* into) { //The starting state is important for the bug. int state = QUOTES; int save_state = BRACKETS; while (qb) { //Always true, it seems this can't just be '1' printf("State is %d\n", state); switch (state) { case BRACKETS: printf("Yay this was correctly executed\n"); exit(0); break; case GENERAL: printf("Oh no how did you get here?\n"); printf("State is %d\n", state); exit(1); break; case QUOTES: state = save_state; printf("State went to %d btw BRACKETS is %d\n", state, BRACKETS); save_state = GENERAL; //Remove this line and it will work even when optimised. printf("After save state, state went to %d btw BRACKETS is %d\n", state, BRACKETS); break; default: ; } printf("State %d btw GENERAL %d\n", state, GENERAL); } printf("If you see this then something is really wrong.\n"); exit(4); } int main() { //These don't seem to matter don't concern yourself with them. char *b = "123"; char out[4]; foo(b, out); return 1; } If I compile this with: gcc -O0 -g -Wall -Werror sillyswitch.c -o sillyswitch It will correctly print "Yay this was correctly executed" However if I compile this with: gcc -O -g -Wall -Werror sillyswitch.c -o sillyswitch It will print "Oh no how did you get here?" I suspect this is a bug. I am unable to create an account to report this as a bug though. -Luke