Auto Initialization of local variables

前端 未结 2 351
醉梦人生
醉梦人生 2020-12-11 10:26

I have the following code snippet.

int j;
printf(\"%d\",j);

As expected, I get a garbage value.

32039491

2条回答
  •  误落风尘
    2020-12-11 11:16

    As expected, I get a garbage value.

    Then your expectation is unjustifiably hopeful. When you use the indeterminate value of an uninitialized object, you generally get (and for your code snippets alone you do get) undefined behavior. Printing a garbage value is but one of infinitely many possible manifestations.

    I always thought local variables are initialized to a garbage value by default, but it looks like variables get auto initialized when a loop is used.

    You thought wrong, and you're also drawing the wrong conclusion. Both of your code snippets, when standing alone, exhibit undefined behavior. You cannot safely rely on any particular result.

提交回复
热议问题