2

I have a static structure p defined in a C file like below (all the below code is in the same file). However, when I compile, I see that the compiler optimizes p out (in the .o file, hence this doesn't reach the linker). Here p is not 'unused' and is written once, but not read back anywhere.

How does the compiler decide to optimize it out ? Can anyone point me to any documentation describing this?

static struct 
{
    int p1;
    int p2;
}p;

static void foo(void) //this is getting inlined..
{
    p.p1 = 10;
    p.p2 = 20;
}

void foo1(void)
{
    blah();
    foo();
    blah1();
}

If I make p volatile, it is not getting optimized anyway.

spenibus
  • 4,339
  • 11
  • 26
  • 35
BlueScreen
  • 21
  • 2
  • 1
    which compiler do you use? – chris Oct 15 '15 at 09:39
  • what do you mean by "optimizing it out"? is the content of `foo` getting inline or is it omitted altogether? – MByD Oct 15 '15 at 09:53
  • What the compiler is allowed to optimise out is defined by the C standard. Known as the "as-if" rule. See [this answer](http://stackoverflow.com/questions/15718262/what-exactly-is-the-as-if-rule?answertab=active#tab-top) for a good explanation. – kaylum Oct 15 '15 at 10:03
  • @kaylum The "as-if" rule is defined in the C++ standard. This question is about C. Or am I missing something? – sergej Oct 15 '15 at 10:07
  • @sergej You are right in that it is defined much more clearly in the C++ standard. But the C standard also references it - albeit not so clearly. And the intention is the same. Search for it in the C standard and it will show up in a surprising way :-) – kaylum Oct 15 '15 at 10:08
  • 3
    Specifically, section 5.1.2.3, point 4: "An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or accessing a volatile object).". And point 6 which defines "observable behaviour". – kaylum Oct 15 '15 at 10:13
  • 1
    @kaylum That is the answer. – sergej Oct 15 '15 at 10:19

0 Answers0