Initialise a variable to its own undefined value

前端 未结 4 659
你的背包
你的背包 2021-02-04 01:50

In C, does initialising a variable to it\'s own value make sense? If yes, what for?

Allow me to elaborate. In Git sources there are some examples of initialising a varia

4条回答
  •  别跟我提以往
    2021-02-04 02:26

    This compiles because Standard C99 §6.2.1/7 says:

    Any identifier that is not a structure, union, or enumeration tag "has scope that begins just after the completion of its declarator." The declarator is followed by the initializer.

    However, value of status is Indeterminate. And you cannot rely on it being initialized to something meaningful.

    How does it work?
    int status creates an space for the variable to exist on the stack(local storage) which is then further read to perform status = status, status might get initialized to any value that was present in the stack frame.

    How can you guard against such self Initialization?
    gcc provides a specific setting to detect self Initializations and report them as errors:

    -Werror=uninitialized -Winit-self

    Why is it used in this code?
    The only reason I can think it is being used in the said code is to suppress the unused variable warning for ex: In transport.c, if the control never goes inside the while loop then in that control flow cmp will be unused and the compiler must be generating a warning for it. Same scenario seems to be with status variable in wt-status.c

提交回复
热议问题