Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

c - Any guarantees for uninitialised variables?

There are many claims that any use of uninitialised variables invokes undefined behavior (UB).
Perusing the docs, I could not verify that claim, so I would like a convincing argument clarifying this for both C and C++.
I expect the same semantics for both, but am prepared to be surprised by subtle or not so subtle differences.

Some examples of using uninitialised variables to get started. Please add others as needed to explain any corner-cases they don't cover.

void test1() {
    int x;
    printf("%d", x);
}

void test2() {
    int x;
    for(int i = 0; i < CHAR_BIT * sizeof x)
        x = x << 1;
    printf("%d", x);
}

void test3() {
    unsigned x;
    printf("%u", x); /* was format "%d" */
}

void test4() {
    unsigned x;
    for(int i = 0; i < CHAR_BIT * sizeof x)
        x = x << 1;
    printf("%u", x); /* was format "%d" */
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In C all of them are undefined behavior, but for a reason that probably not comes directly to mind. Accessing an object with indeterminate value has undefined behavior if it is "memoryless" that is 6.3.2.1 p2

If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.

Otherwise, if the address is taken, the interpretation of what indeterminate means concretely in this case is not unanimous. There are people that expect such a value to be fixed once it is first read, others speak of something like "woobly" (or so) values that can be different at each access.

In summary, don't do it. (But that you probably knew already.)

(And not talking about the error using "%d" for an unsigned.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...