|
-
July 26th, 2002, 06:08 AM
#1
Initialization order for constant static data in C++
Gurus,
For quite some time, I have been perplexed by the rules which govern the initialization order of global static constant data. I am under the impression that there is no standardized order for the initialization of global static constant data. I think that it is unspecified both for cases involving variables in one file as well as project-wide variables, possibly made accessible with the extern keyword. Furthermore, I think that it is poor design to rely on an assumed order for global static constant data.
Please look at the sample program below.
There are (at least) three questions that come to mind:
1) Is there a guarantee that the global static constant pi_over_two is initialized at the time of the call of ::acos_1 for the initialization of ::val_acos_1? I think definitely not. Please verify.
2) Is there a guarantee that pi_over_two_local is properly initialized for the execution of ::acos_2 needed by the initialization of ::val_acos_2? I am really uncertain here.
3) How many times does the initialization code for the initialization of local constant variables run? An example is the initialization of pi_over_two_local. Please assume here that the initialization question pertains to codes which actually require run-time, not just which can be handled by the pre-processor. Does such initialization code run once before entry to main? Does it run each and every time the subroutine is called? Does it run once the first time the subroutine is called and not again thereafter. Or is it implementation specific?
Thank you very much.
Sincerely,
Chris
a.k.a. dude_1967
P.S. This post should not be taken as a treatise on the sensible use of mathematical functions.
Code:
#include <iostream>
#include <math.h>
using namespace std;
const double acos_1(const double d);
const double acos_2(const double d);
static const double pi_over_two = 3.1415926535897932384626434 / 2;
static const double val_acos_1 = ::acos_1(0.8);
static const double val_acos_2 = ::acos_2(0.8);
const double acos_1(const double d)
{
// Bad?
// Is there a guarantee that pi_over_two is initialized?
return pi_over_two - ::asin(d);
}
const double acos_2(const double d)
{
// Is there a guarantee that pi_over_two_local is initialized?
// Will the initialization code of pi_over_two_local run more than once?
static const double pi_over_two_local = 3.1415926535897932384626434 / 2;
return pi_over_two_local - ::asin(d);
}
int main(int argc, char* argv[])
{
cout.precision(15);
cout << val_acos_1 << endl;
cout << val_acos_2 << endl;
return 1;
}
You're gonna go blind staring into that box all day.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|