对C与静态存储持续时间对象在C ++初始化 [英] Initialization of Objects with Static Storage Duration in C vs C++

查看:302
本文介绍了对C与静态存储持续时间对象在C ++初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  什么主要的回报?

例如,下面的code编译没有任何警告:

For example, the following code compiles without any warning:

#include <stdio.h>

int i = i + 1;

int main(int argc, char *argv[])
{

    fprintf (stderr, "%d\n", i);

    return 0;
}

我觉得这是在语法上是非法的,因为 I 是它的声明前被使用,是不是?

I think this is illegal in syntax, because i is used before it's declared, is it right?

在我看来,的外观INT I = I + 1; 肯定是错误的,为什么不编译器警告呢?我使用gcc 4.5.1。

And in my opinion, the appearance of int i = i + 1; is surely a bug, why doesn't the compiler warn about it? I use gcc 4.5.1.

推荐答案

(注意:我指的是当前的C ++标准)

(notice: I'm referring to the current C++ standard)

我真的不知道这一点,但是,如果标准我间pretation是正确的,code应该是罚款而不是UB。

I'm not really sure about this, but, if my interpretation of the standard is correct, the code should be fine and not UB.

这是变量的第一次初始化是的与静态存储持续时间对象的零初始化的之前任何其他情况的
初始化发生
的(§3.6.2¶1)。

The first initialization of that variable is the zero-initialization of objects with static storage duration that happens before any other initialization takes place (§3.6.2 ¶1).

所以,首先设置为零。

然后,动态初始化的(即非零和非恒定初始化)发生,所以它使用的电流值i ( 0)实际上再次对其进行初始化。在结束它的值应该为1。

Then, dynamic initialization (i.e. non-zero and non-constant initialization) takes place, so it uses the current value of i (0) to actually initialize it again. At the end it should evaluate to 1.

这似乎被第8.5节¶6证实,明确地说:

This seems confirmed by §8.5 ¶6, that explicitly says:

静态存储持续时间的任何对象占用的内存应为任何其他初始化发生之前在程序启动时初始化为零。 [注:在某些情况下,额外的初始化稍后再进行。 ]

The memory occupied by any object of static storage duration shall be zero-initialized at program startup before any other initialization takes place. [Note: in some cases, additional initialization is done later. ]

(如果你发现在分析一些缺陷,请告诉我的意见,我会很高兴改正/删除了答案,这是地面湿滑,我意识到这一点:))

(If you find some flaw in the analysis please just tell me in the comments and I'll be glad to correct/delete the answer, it's slippery floor and I'm conscious of it :) )

这篇关于对C与静态存储持续时间对象在C ++初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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