任何担保,未初始化的变量? [英] Any guarantees for uninitialised variables?

查看:220
本文介绍了任何担保,未初始化的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多种说法,任何使用未初始化变量将调用<一个href=\"http://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior\">undefined行为(UB)。结果
仔细阅读该文档,我无法确认这种说法,所以我想一个令人信服的论据澄清这一为C和C ++。结果
我希望两个相同的语义,但我prepared通过微妙的或不那么细微的差别感到惊讶。

使用未初始化变量的一些例子开始。根据需要来解释它们不包括任何角落的情况下,请添加其他。

 无效test1的(){
    INT X;
    的printf(%D,X);
}空TEST2(){
    INT X;
    的for(int i = 0; I&LT; CHAR_BIT * sizeof的X)
        X = X&所述;&下; 1;
    的printf(%D,X);
}无效TEST3(){
    无符号X;
    的printf(%U,X); / *为格式%d个* /
}无效TEST4(){
    无符号X;
    的for(int i = 0; I&LT; CHAR_BIT * sizeof的X)
        X = X&所述;&下; 1;
    的printf(%U,X); / *为格式%d个* /
}


解决方案

在C个个都是不确定的行为,但对于可能不会直接出现在脑海的一个原因。访问与不确定值的对象不确定的行为,如果它是
记忆,也就是6.3.2.1 P2


  

如果左值指定自动存储持续时间的对象,
  可能已宣布与寄存器存储类(从未有过
  其地址获取),并且该对象是未初始化(未声明
  有一个初始化并没有分配给它之前已经被执行
  使用),则该行为是不确定的。


否则,如果该地址被占用,什么不确定在这种情况下具体是指间pretation并不一致。有迹象表明,期望一旦它首先读取所定的价值,别人的东西,如woobly(或左右)的值,可以在每个接入不同的说话。

在总之,不要做它。 (但你可能知道了。)

(而不是使用%d表示一个谈论的错误签名

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" */
}

解决方案

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.)

这篇关于任何担保,未初始化的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆