为什么一些const变量引用一些导出的const变量获得值0? [英] Why do some const variables referring to some exported const variables get the value 0?

查看:268
本文介绍了为什么一些const变量引用一些导出的const变量获得值0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下几点。我有两个导出的常量如下:

Consider the following. I have two exported constants as follows:

// somefile.h
extern const double cMyConstDouble;
extern const double cMyConstDouble2;

// somefile.cpp
const double cMyConstDouble = 3.14;
const double cMyConstDouble2 = 2.5*cMyConstDouble;

这些常量现在被引用一些地方来定义两个静态(本地可见)常量:

These constants are now referenced some place else to define two static (locally visible) constants:

// someotherfile.cpp
#include "somefile.h"
static const double cAnotherDouble = 1.1*cMyConstDouble;
static const double cAnotherDouble2 = 1.1*cMyConstDouble2;
printf("cAnotherDouble = %g, cAnotherDouble2 = %g\n",
       cAnotherDouble, cAnotherDouble2);

其中产生以下输出:

cAnotherDouble = 3.454, cAnotherDouble2 = 0

为什么是第二个双0?我正在使用.NET 2003 C ++编译器(13.10.3077)。

Why is the second double 0? I'm using .NET 2003 C++ compiler (13.10.3077).

推荐答案

因为cMyConstDouble被声明为extern,编译器不是能够承担其值并且不会为cMyConstDouble2生成编译时初始化。由于cMyConstDouble2没有编译时间初始化,所以初始化顺序相对于cAnotherDouble2的顺序是随机的(undefined)。有关更多信息,请参见静态初始化失败信息。

Because cMyConstDouble is declared as extern, compiler is not able to assume its value and does not generate a compile time initialization for cMyConstDouble2. As the cMyConstDouble2 is not compile time initialized, its order of initialization relative to cAnotherDouble2 is random (undefined). See static initialization fiasco for more information.

这篇关于为什么一些const变量引用一些导出的const变量获得值0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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