4

This Question is about getting the gcc compiler to warn when you make a typo and initialize a variable with itself.

      int f()
      {
        int i = i;
        return i;
      }

It turns out you need the -Winit-self flag in addition to -Wuninitialized:

-Winit-self (C, C++, Objective-C and Objective-C++ only) Warn about uninitialized variables which are initialized with themselves. Note this option can only be used with the -Wuninitialized option, which in turn only works with -O1 and above.

My question is: Why is this not the default behavior for -Wuninitialized? What is the use case where you want to warn about uninitialized variables, but not self-initialized ones, which are just as troublesome?

Community
  • 1
  • 1
AShelly
  • 34,686
  • 15
  • 91
  • 152

1 Answers1

2

It looks like this bug report Warn about member variables initialized with itself has an explanation for this (emphasis mine):

I agree with Andrew, the a(a) mistake should always warn, it should be independent of -Winit-self, which exists so that -Wuninitialized doesn't warn about the common (but questionable) practice of self-initializing automatic variables to silence warnings.

It it probably called a questionable practice since it is undefined behavior in C++ to self initialize an automatic variable and the bug report is a C++ bug report.

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • This happens sometimes when initialization is unimportant, like filling a 32-bit number bit-by-bit (consider permuting another 32-bit number by a known permutation). In this case initialization is unimportant, and could confuse someone on how the algorithm works, so you can use the idom `uint32_t val = val;` to indicate to the reader that you are intentionally leaving the value uninitialized. – Steve Cox Apr 09 '14 at 14:57
  • @SteveCox sure, I can see that but it is still questionable since it is undefined behavior and compilers can do odd things with undefined behavior. – Shafik Yaghmour Apr 09 '14 at 15:12
  • Definitely, I don't actually do this, I've just seen it in places where people wanted to urge the compiler not to actually put in the `xor eax,eax` but still wanted to hide an uninitialized variable warning. – Steve Cox Apr 09 '14 at 16:03
  • 1
    @ShafikYaghmour: It's tragic that compiler writers have lost sight of the fact that when the Standard leaves a behavior undefined, that is meant as an invitation to implementers to *exercise judgment* about the cases where their implementation should treat it as defined, rather than as an invitation to throw judgment out the window. The behavior of some compiler writers would only make sense if they interpreted it as the latter. – supercat Feb 21 '17 at 20:11