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

查看:178
本文介绍了为什么一些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的初始化顺序是随机的(未定义的)。有关详细信息,请参见静态初始化fiasco

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天全站免登陆