By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,134 Members | 1,874 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,134 IT Pros & Developers. It's quick & easy.

initializing constant variable from file

P: 3
I need a constant that should not change after initialization. Initialization value is stored in a file. How can i do this? The obvious way is to skip the "const" part and use it freely as a variable, which i resent, as it is really a constant.
Nov 7 '06 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 5K+
P: 8,916
It isn't a const as far as the program is concerned because it starts with some value and then some time into running the program (the time it takes to open and read the required value) you change it's value to something else.

If you really wanted to you could encapsulate it in a class and then when you read the required value instantiate a new instance of the class initialising the constant member to the required value.

Or you can do something sneaky like have a variable that is only accessed by the code reading the value from the file and a const reference to the variable used everywhere else.

Expand|Select|Wrap|Line Numbers
  1.     int _value = 5;
  2.     const int &ConstValue = _value;
Nov 7 '06 #2

P: 3
Forgot to mention that I was trying it in C, not C++. To simplify, consider a 3 member structure, all members constant type. The first two members are initialized directly and the 3rd I must input from a file. Because these const members are "virtually equal" for this program, it doesn't make sense for me to be forced to remove the const from the third member, simply because I don't know how to fool C to initialize it. Anyone?
Expand|Select|Wrap|Line Numbers
  1. typedef struct {
  2.     const char *a;
  3.     const int c;
  4.     const int b;
  5. } a_t;
  7. a_t ar[] = {
  8. {"asd", 3 },
  9. {"wer", 2 },
  10. {"sdf", 2 }
  11. };
Nov 7 '06 #3

Post your reply

Sign in to post your reply or Sign up for a free account.