C++ Assign a const value at run-time? - c++

I have a constant value that never changes during run-time, but is impossible to know until run-time.
Is there a way to declare a constant (either as a member of a class or not) without defining it and also assign a computed value once (and only once) it is determined; or am I going to have to resort to a non-const declaration and use coding S & Ps (ALL_CAPS variables names, static declaration if in a class, etc.) to try and keep it from changing?
CLARIFICATION:
Though these are good answers, the real-world situation I have is more complicated:
The program has a main loop that continually runs between processing and rendering; the user can set required options and once they are set they will never change until the program is restart. An "Initialize" function is set up for anything that can be determined before the main loop, but values that are dependent on user interaction must be performed in the middle of the loop during the processing phase. (At the moment, persistent data storage techniques come to mind...)

Something like this?
const int x = calcConstant();
If it's a class member, then use the constructor initialisation list, as in Yuushi's answer.

You can define it in a struct or class and utilize an initialisation list:
#include <iostream>
struct has_const_member
{
const int x;
has_const_member(int x_)
: x(x_)
{ }
};
int main()
{
int foo = 0;
std::cin >> foo;
has_const_member h(foo);
std::cout << h.x << "\n";
return 0;
}

As a static or function-local variable:
const int x = calcConstant();
As a class member:
struct ConstContainer {
ConstContainer(int x) : x(x) {}
const int x;
};

Yes, you can make a private static singleton field with an initialization method and a gettor method. Here's an example of how to do it:
// In foo.h
class Foo
{
public:
// Caller must ensure that initializeGlobalValue
// was already called.
static int getGlobalValue() {
if (!initialized) {
... handle the error ...
}
return global_value;
}
static void initializeGlobalValue(...)
private:
static bool initialized;
static int global_value;
};
// In foo.cpp
bool Foo::initialized = false;
int Foo::global_value;
void Foo::initializeGlobalValue(...) {
if (initialized) {
...handle the error...
}
global_value = ...;
initialized = true;
}

Related

Is it possible to use a static variable declared in another C++ library

I intend to use a library with a declaration of a variable in one of its function
/// in library A
function fun(){
static int iwanttouse = 1;
/// operation on iwanttouse
}
How can i use it in Application B? Do I connect it with extern
extern int iwanttouse;
// and then use it
if(iwanttouse == x)
.....
or I could use them without declaration?
No. Static variables have internal linkage, precisely so that you can't do that.
Don't use global variables, they make unit testing of your code next to impossible, use dependency injection instead.
Example:
#include <iostream>
// header file.
// Define a struct with all the data you need globally
struct my_data_t
{
bool i_want_house = true;
};
// Get a static instance
my_data_t& getGlobalData()
{
static my_data_t data;
return data;
};
// Put code where you want to use data in a class.
class my_class_t
{
public:
// constructor with dependency injection!
// this way any data can be injected (valuable for unit testing!)
explicit my_class_t(my_data_t& data) :
m_data{ data }
{
}
void show_i_want_house()
{
// use data
if (m_data.i_want_house)
{
std::cout << "I really want that house!\n";
}
else
{
std::cout << "Nah, this house is not good enough\n";
}
}
private:
my_data_t& m_data;
};
// cpp file
int main()
{
// instantiate objects with a reference to the data you want it to use.
my_class_t object_with_global_data{ getGlobalData() };
object_with_global_data.show_i_want_house();
my_data_t test_data{ false }; //aggregate initialization of struct
my_class_t object_with_test_data{ test_data }; //create an object with non-global data for testing
object_with_test_data.show_i_want_house();
return 0;
}
A variable marked with the keyword static(outside the class) is only visible to that translation unit. static elements are allocated storage only once in a program lifetime in static storage area. And they have a scope till the program lifetime.
So in your case, static int iwanttouse = 1; is not even seen by another translation unit. :)

C++ global variable that can be changed only in one method, possible?

I'm looking for a way to have an int variable that persists value across method calls. From this perspective a class member will be good.
But I would like that int variable to be changed in only one particular method.
How do I make that?
I tough about
void MyClass::my_method(){
static int var = 0;
var++;
}
But, I would like var = 0; to be executed only the first time.
void my_method(){
static int var;
var++;
}
The problem here is, that
static int var;
is only visible in the local scope of my_method().
You can make it global just by definition of that variable outside of my_method():
int var;
void my_method() {
var++;
}
but var will be visible for everyone.
The better way is to encapsulate all of that into a class:
class MyClass {
public:
static void my_method() {
var++;
}
private:
static int var = 0;
};
You can use the following key access pattern:
struct Foo {
void fun1();
void fun2();
static class Var {
friend void Foo::fun1();
int i = 0;
public:
int value() const { return i; }
} var;
};
Foo::Var Foo::var;
void Foo::fun1() { var.i = 42; }
void Foo::fun2() {
// var.i = 42; // this will generate compile error cause fun2 doesn't have to var
}
Live Demo
This way only the member functions of Foo that are declared friends in wrapper class Var can change its private member variables (e.g., var.i).
var is just locally, if you want that to be 0 the first time the function returns make it initialized to -1 or if 0 is just right you are ok. As is var is only visible inside my_method so if you want that to be visible to all the class you have to put it outside and use only my_method to modify the value.
I don't have enough rep to comment yet, But you should note that Static is not equal to Constant.
Static variables maintain their value for ALL instances of a class, whereas Constant variables can have different values for each instance (object) of a class.
See this question for a more in-depth explanation.
What is the difference between a static and const variable?
To answer your question directly, you cannot have a true "Global" vairable that is only editable from one class. Instead, you should consider πάντα ῥεῖ 's answer OR wait to declare the constant until after you know the value you would like to assign to it. For instance, I want to store X+10 to a constant variable Y
int x = 5 //create variable
//Do whatever you need to do to get the value
function myFunction(){
x = x + 10;
}
const int y = x; //now Y = 15 and cannot be changed.

How to invoke struct member functions based on return value of a bool type member function?

I want to do some conditional checks within a bool member function of a struct. How will my struct object struct1 know the bool member function has returned true, so that integers a & b can be used within the calc member function?
int main() {
vector<Point> pt;
pt.push_back(Point{ 1.5, 4.2 });
pt.push_back(Point{ 2.4, 3.1 });
doSth struct1;
bool tempbool = struct1.memfuncbool(pt); //error starts here!
if (tempbool) {int answer = struct1.calc(1);} //??
std::cout << answer;
return 0;
}
struct Point {
double _x;
double _y;
};
struct doSth {
int a, b; //data members
int calc(const int k) {
return (a + b)*k;
}
bool memfuncbool(const vector<Point> &pts) {
//does stuff...
a = var1; //var1 = 1
b = var2; //var2 = 2
return true;
}
}
There are two approaches: encapsulation for caller safety and pure code discipline. In the later you yourself make sure that the code you write is always aware of the latest result of memfuncbool and when and where a and b are set.
In the first you can add a flag in your struct that you set once memfuncbool is called and check in calc (and handle it appropriately.) In that case you should also make sure that the flag is cleared when initialising your struct - either via constructor or again code discipline (like always zero your structs).
An information hiding approach (C++) in the first sense would look like this:
class DoSth {
int a, b;
bool valid;
public:
DoSth() : valid(false) { }
bool isValid() const { return valid; }
/// returns calc if valid, otherwise 0
int calc(int k) const {
return isValid() ? (a + b) * k : 0;
}
void setSth(...) {
a = ...
b = ...
valid = true;
// instead of returning here the caller can check isValid() anytime
}
};
Your code has many issues that could easily be solved if you didn't try to do more than you know.
1 You're defining both Point and doSth structures AFTER the main function. So the main function has no way to know what your structures do. Normally you would use a header file to contain the declaration and the cpp file to contain the implementation, but since you're doing a small program you can just move the definitions of your structures to be above the main function. Alternatively you can declare your structures above main and implement them below, like this.
// Definition of struct Point
struct Point {
double _x;
double _y;
};
// Definition of struct doSth
struct doSth {
int a, b; //data members
// **Declaration** of doSth methods
int calc(const int k);
bool memfuncbool(const std::vector<Point> &pts);
};
int main() {
...
}
// Definition of calc method
int doSth::calc(const int k) {
...
}
// Definition of memfuncbool method
bool doSth::memfuncbool(const std::vector<Point> &pts) {
...
}
2 In the main function you're using a variable called answer in a scope that doesn't know such variable.
if (tempbool) {
int answer = struct1.calc(1);
}
std::cout << answer; // ERROR: answer is not a known variable
See, you're declaring a variable inside an if condition but using it outside. You have to declare the variable outside as well if you want to use it.
int answer = 0;
if ( tempbool ) {
answer = struct1.calc(1);
}
std::cout << answer << std::endl; // OK
OR
if ( tempbool ) {
int answer = strut1.calc(1);
std::cout << answer << std::endl;
}
else {
std::cout << "Invalid result!" << std::endl;
}
This is a fix to compile what you have done so far. But this is not a solution to your code design question.
3 Code Design
Although I suggested quick fixes to your code your actual problem has to do with how you design your classes and structure your code. I've showed you what you did wrong in your code, but your problem can be solved using a better structured approach.
While writing my answer Beyeler already answered this part for you, so check his answer.
EDIT
In your code you are probably doing
using namespace std;
But you've written both vector< Point > and std::cout. You should not use the using line, to begin with, to avoid name collisions and to help YOU know where this vector is coming from.
However, if you insist on using this line so you don't have to write std:: (and it's OK if you know what you're doing), don't go typing std:: on one thing and then omit it in another. Be consistent, either use it or don't.
I found three errors with your code:
"do" is a c++ keyword. You can't use it to name structs.
The parameter of the "memfuncbool" is missing its type. const& is not a type.
Missing semicolon after struct definition.
Also i supposed that var1, var2 and arg are well defined. If they are not even that is a error.
After correcting these errors maybe you can do something like-
if(tempbool) { /*statements*/ };

Static function needing to deal with members of a C++ class

I have to make some kind of bridge between two pieces of software, but am facing an issue I don't know how to deal with. Hopefully someone will have interesting and (preferably) working suggestions.
Here is the background : I have a C++ software suite. I have to replace some function within a given class with another function, which is ok. The problem is that the new function calls another function which has to be static, but has to deal with members of the class. This is this second function which is making me mad.
If the function is not static I get the following error :
error: argument of type ‘void (MyClass::)(…)’ does not match ‘void (*)(…)’
If I set it to static I get either the following error :
error: cannot call member function ‘void
MyClass::MyFunction(const double *)’ without object
or
error: ‘this’ is unavailable for static member functions
depending on if I use or not the "this" keyword ("Function()" or "this->Function()").
And finally, the class object requires some arguments which I cannot pass to the static function (I cannot modify the static function prototype), which prevents me to create a new instance within the static function itself.
How would you deal with such a case with minimal rewriting ?
Edit : Ok, here is a simplified sample on what I have to do, hoping it is clear and correct :
// This function is called by another class on an instance of MyClass
MyClass::BigFunction()
{
…
// Call of a function from an external piece of code,
// which prototype I cannot change
XFunction(fcn, some more args);
…
}
// This function has to be static and I cannot change its prototype,
// for it to be passed to XFunction. XFunction makes iterations on it
// changing parameters (likelihood maximization) which do not appear
// on this sample
void MyClass::fcn(some args, typeN& result)
{
// doesn't work because fcn is static
result = SomeComputation();
// doesn't work, for the same reason
result = this->SomeComputation();
// doesn't work either, because MyClass has many parameters
// which have to be set
MyClass *tmp = new MyClass();
result = tmp->SomeComputation();
}
Pointers to non-static member functions are a bit tricky to deal with. The simplest workaround would just be to add an opaque pointer argument to your function which you can then cast as a pointer to 'this', then do what you need with it.
Here's a very simple example:
void doSomething(int (*callback)(void *usrPtr), void *usrPtr)
{
// Do stuff...
int value = callback(usrPtr);
cout << value << "\n";
}
class MyClass
{
public:
void things()
{
value_ = 42;
doSomething(myCallback, this);
}
private:
int value_;
static int myCallback(void *usrPtr)
{
MyClass *parent = static_cast<MyClass *>(usrPtr);
return parent->value_;
}
};
int main()
{
MyClass object;
object.things();
return 0;
}
In this example myCallback() can access the private value_ through the opaque pointer.
If you want a more C++-like approach you could look into using Boost.Function and Boost.Bind which allow you to pass non-static member functions as callbacks:
void doSomething(boost::function<int ()> callback)
{
// Do stuff...
int value = callback();
cout << value << "\n";
}
class MyClass
{
public:
void things()
{
value_ = 42;
doSomething(boost::bind(&MyClass::myCallback, this));
}
private:
int value_;
int myCallback()
{
return value_;
}
};
int main()
{
MyClass object;
object.things();
return 0;
}
If you really can't change the function prototype you could use a global pointer, but that opens up all sorts of issues if you will ever have more than one instance of your class. It's just generally bad practice.
class MyClass;
static MyClass *myClass;
void doSomething(int (*callback)())
{
// Do stuff...
int value = callback();
cout << value << "\n";
}
class MyClass
{
public:
void things()
{
value_ = 42;
myClass = this;
doSomething(myCallback);
}
private:
int value_;
static int myCallback()
{
return myClass->value_;
}
};
int main()
{
MyClass object;
object.things();
return 0;
}
Following spencercw's suggestion below the initial question I tried the "static member variable that you set to point to this" solution (the global variable would have been tricky and dangerous within the context of the software suite).
Actually I figured out there was already something like this implemented in the code (which I didn't write) :
static void* currentObject;
So I just used it, as
((MyClass*)currentObject)->SomeComputation();
It does work, thanks !!!
non-reentrant and non-thread-safe way is to pass "this" address using global variable.
You can move the result = SomeComputation(); out of your static function and place it in BigFunction right before your call to the static function.

c++ redefine variable as constant

I have a struct:
struct s
{
UINT_PTR B_ID;
};
s d;
d.B_ID=0x1;
That works fine, but I want d.B_ID to be constant. I tried to use (const) but it didn't work. So after I put a value to d.B_ID, then I want make it a constant.
Any ideas?
EDIT
ok i don't want the whole struct a constant.
when i set timer and use the b.B_ID as an idea for the timer.
in the
switch(wparam)
{
case b.B_ID // error: B_ID must be constant
....
break;
}
so that is why i need it to be a constant
Variable modifiers are fixed at compile time for each variable. You may have to explain the context of what you are trying to do, but perhaps this will suit your needs?
struct s
{
int* const B_ID;
};
int main (void) {
int n = 5;
s d = {&n};
int* value = d.B_ID; // ok
// d.B_ID = &n; // error
return 0;
}
Since you are using C++ I would recommend:
class s {
public:
int* const B_ID;
s (int* id) :
B_ID (id) {
}
};
void main (void) {
int n = 5;
s my_s_variable = s(&n);
int* value = my_s_variable.B_ID; // ok
//my_s_variable.B_ID = &n; // error
return 0;
}
Ramiz Toma: well i need way to do it using the s.B_ID=something
In C/C++ type modifiers (like const) are declared at run time for a given type and cannot be changed at run time. This means that if a variable is declared const it can never be assigned to using the assignment operator. It will only be assigned a value when it is constructed.
This is not a problem however because you can always get around this by proper design.
If you say you need to use assignment, I assume that this is because you create the struct before you know what the value of the variable will be. If this is the case then you simply need to move the struct declaration till after you know the value.
For example
s d; //variable declaration
//calculate B_ID
//...
int* n = 5;
//...
d.B_ID = &n;
This will not work, because if you want b.D_ID to be 'un assignable' it will always be so. You will need to refactor your code similarly to:
//calculate B_ID
//...
int* n = 5;
//...
s d (&n);
//good
struct s
{
s() : B_ID(0){}
UINT_PTR const B_ID;
};
int main(){
s d;
d.B_ID=0x1; // error
}
EDIT: Sorry, here is the updated code snippet in C++
struct s
{
s(UINT_PTR const &val) : B_ID(val){}
UINT_PTR const B_ID;
};
int main(){
s d(1);
d.B_ID=0x1; // error
}
In C++ language the case label must be built from an Integral Constant Expression (ICE). ICE is what the compiler implies under the term "constant" in your error message. A non-static member of a class cannot be used in an ICE. It is not possible to do literally what you are trying to do. I.e. it is not possible to use a struct member in a case label.
Forget about switch/case in this context. Use ordinary if branching instead of switch statement.
You can't do that - ie. it is not possible to selectively make a single member of a struct const. One option is to 'constify' the entire struct:
s d;
d.B_ID=0x1;
const s cs = s; // when using this B_ID won't be modifiable - but nor would any other members
Or you could set it at construction:
struct s
{
s(UINT_PTR const p): B_ID(p) {}
UINT_PTR const B_ID;
};
s d(0xabcdef);
Another way would be a getter and a one time setter
class s
{
private:
bool m_initialized;
UINT_PTR m_value;
public:
s() : m_initialized(false), m_value(NULL) {}
s(UINT_PTR value) : m_initialized(true), m_value(value) {}
//no need for copy / assignment operators - the default works
inline UINT_PTR GetValue() const { return m_value; } //getter
bool SetValue(UINT_PTR value) //works only one time
{
if (m_initialized)
{
m_value = value;
m_initialized=true;
return true;
}
else
{
return false;
}
}
inline bool IsInitialized() const { return m_initialized; }
};