I'm working in C++ and I need to know if a scalar value (for instance a double
) is "defined" or not. I also need to be able to "undef" it if needed:
class Foo {
public:
double get_bar();
private:
double bar;
void calculate_bar() {
bar = something();
}
};
double Foo::get_bar() {
if ( undefined(bar) )
calculate_bar();
return bar;
}
Is it possible in C++?
Thanks
Why not maintain a separate flag that gets initialized to false and then gets set to true when bar is calculated. It can then be 'undefed' by setting the flag to false again.
If you mean at run-time, there is no such thing. If
bar
is never initialized, it will have whatever random bits happen to be there, depending on how the object is allocated (some allocators will initialize new memory to all-zero).edit: it's up to the programmer to handle object state in constructors and/or manual initialization methods like
init()
As others pointed out, there is nothing like an "undefined" state. But you may want to look into boost.optional
C++ does not have an "undefined" state for primitive types. The closest available for float/double would be NAN, but that really has a different meaning.
This is not possible in C/C++, primitives will always a value assigned (mostly garbage, whatever was on that spot in memory before it, unless explicitly assigned at declaration). I's common to have a placeholder value (i.e. 0 for pointers) which denotes not-used, however these have to be explicitly assigned as well. If your double can take on any value, then I suggest you put a boolean next to it, assigned to false initially, and test/set that one when you want to do your calculation.
Initialize
bar
to some value which can never occur when you call thesomething()
function in the constructor.For example:
Then check for the value
-1
in theget_bar
function.(hmmm Laserallan also posted that answer 1 minute before :-( ;-) )