我在一个非常大的应用程序中发现了这个问题,并从中制作了一个 SSCCE。我不知道代码是否有未定义的行为或-O2
破坏它。
用gcc a.c -o a.exe -O2 -Wall -Wextra -Werror
它编译时会打印5。
但是当编译时没有(例如)或取消注释 2 条注释行之一(防止内联)时,它会打印25 。-O2
-O1
#include <stdio.h>
#include <stdlib.h>
// __attribute__((noinline))
int f(int* todos, int input) {
int* cur = todos-1; // fixes the ++ at the beginning of the loop
int result = input;
while(1) {
cur++;
int ch = *cur;
// printf("(%i)\n", ch);
switch(ch) {
case 0:;
goto end;
case 1:;
result = result*result;
break;
}
}
end:
return result;
}
int main() {
int todos[] = { 1, 0}; // 1:square, 0:end
int input = 5;
int result = f(todos, input);
printf("=%i\n", result);
printf("end\n");
return 0;
}
GCC 的选项是-O2
破坏这个小程序还是我在某处有未定义的行为?