Uninitialized variable in C

前端 未结 5 1079
滥情空心
滥情空心 2020-12-07 03:15

I\'m a little bit confused. As far as I know, if you declare an int in C, without initializing it, for e.g: int x;

so its value is indeterminate. So if

5条回答
  •  [愿得一人]
    2020-12-07 04:03

    Using an uninitialized value does not directly cause undefined behavior.

    Per C 2011 (n1570 draft) 6.7.9 10, an uninitialized object with automatic storage duration has indeterminate value. Per 3.19.2 1, an indeterminate value is either an unspecified value or a trap representation. Similar text appears in C 1999.

    If the object has a trap representation, then undefined behavior may occur. However, if the object has an unspecified value, then program must behave has if the object has some determinate value; it is merely not specified which value the object has. The program is not permitted to crash merely because the value is unspecified.

    It is surprising that you report the simple program shown crashes in Visual Studio 2010, because I do not expect that the int type has any trap representations in Visual Studio 2010. It may be that some source file other than what you expected was compiled and crashed or that you have enabled special debugging features in Visual Studio 2010 that attempt to track uninitialized objects (but fail in the second case where you use foo).

    I suggest you repeat the test from scratch, pasting the code you displayed in this question into a new file and compiling that new file with default options.

    Of course, Visual Studio 2010 does not conform to the C standard, not even the old 1999 standard, so it is not bound to obey the above clauses. In effect, everything about Visual Studio 2010 is undefined behavior with regard to the C standard.

提交回复
热议问题