Compiler flag in GCC (C)

1.8k Views Asked by At

I have read the GCC documentation and man. If I compile the code as (1) gcc -o test test.c I get some results when executing it. If I compile it as (2) gcc -O -o test test.c I get different results when I run it.

Reading the GCC man, I compile using (instead of -O) all the options that the man says that the option -O active. I do not obtain the same result as in the option (2). The result is that of the sentence (1). What does (and not documented) change the behavior of the generated program? The test code:

#include <stdio.h>

int var1 = 0;
int var2 = 0;

int main() {
    int *pntr = &var2;
    pntr--;
    (*pntr) = 99;
    printf("Var1=%d\n",var1);
    printf("Var2=%d\n",var2);
}
1

There are 1 best solutions below

0
On

No UB no problems

#include <stdio.h>

union 
{
  struct
  {
    int var1;
    int var2;
  };
  int arr[2];
}u;

int main() {
    int *pntr = &u.arr[1];
    pntr--;
    (*pntr) = 99;
    printf("Var1=%d\n",u.var1);
    printf("Var2=%d\n",u.var2);
}