0
int abc = abc;
printf ("%d",abc);

What does initializing a variable to itself do? My compiler gives the output 0 .

Hovewer, a source that I can't trust says "The address of the variable abc will be printed.". But it doesn't give a reason, and I am confused by this explanation because we are using the format specifier "%d".

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • `abc` is unitialized. You're getting `0` but it could be anything (garbage). – Fiddling Bits Jun 19 '20 at 13:49
  • 1
    easy-to-find dupe of [What's the behavior of an uninitialized variable used as its own initializer?](https://stackoverflow.com/questions/54200465/whats-the-behavior-of-an-uninitialized-variable-used-as-its-own-initializer) – underscore_d Jun 19 '20 at 13:50
  • And why is it valid? How is it even compiled? –  Jun 19 '20 at 13:50
  • 1
    Research "undefined behaviour". That, like the question itself, is well discussed already. – underscore_d Jun 19 '20 at 13:50
  • 2
    It's not a compilation (syntactical) error. It's a logic error. C doesn't check for logic errors and assumes the programmer knows what they're doing. – Fiddling Bits Jun 19 '20 at 13:51
  • The address of `abc` is `&abc`. – Fiddling Bits Jun 19 '20 at 13:51
  • Another dupe https://stackoverflow.com/questions/8284309/initialise-a-variable-to-its-own-undefined-value – cigien Jun 19 '20 at 13:52
  • I actually surfed in stack overflow for this but didn't know the term of "uninitialized" so I asked this question, sorry. –  Jun 19 '20 at 13:52
  • Read [n1570](https://web.cs.dal.ca/~vlado/pl/C_Standard_2011-n1570.pdf) and [more about undefined behavior](http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html). See also [this draft report](http://starynkevitch.net/Basile/bismon-chariot-doc.pdf) – Basile Starynkevitch Jun 19 '20 at 13:53
  • "expected output of initializing a variable to itself?" -- it depends on the kind of variable: `unsigned char` or not, `register` or not. – chux - Reinstate Monica Jun 19 '20 at 14:08

0 Answers0