3
int main(void) {
  int foo = foo;
  return 0;
}

Why is this possible to do? Wouldn't it be better if this was caught by the compiler?

Benjamin Smus
  • 103
  • 1
  • 7
  • 4
    Unfortunately it's valid C syntax. It makes no sense, but is still valid. And if you build with the right options [you will get warnings about it](https://godbolt.org/z/sTGfE3rEf). – Some programmer dude Feb 22 '23 at 09:25
  • 1
    FWIW, clang issues a warning (`-Wuninitialized`) for this, and GCC seems to do so as well but only in C++ mode. It is _caught_ by the compiler, but as @Someprogrammerdude points out it is valid C so the compiler is not allowed to reject it. – You Feb 22 '23 at 09:29
  • 2
    Related question: [Why is -Winit-self separate from -Wuninitialized](https://stackoverflow.com/q/22965414/147845) – You Feb 22 '23 at 09:31
  • As a side note, code like `volatile uint32_t foo = foo;` might make sense apart from it being undefined behavior. You might want to clear all set flags in a hardware flag register while preserving other flags - if this is done while writing a 1 to them then that's a valid use-case scenario. Though it would be more sensible and well-defined to do `volatile uint32_t tmp = the_register; the_register = tmp;`. – Lundin Feb 22 '23 at 14:04

0 Answers0