Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value of an integer?

Tags:

c++

My program requires several floats to be set to a default number when the program launches. As the program runs these integers will be set to their true values. These true values however can be any real number. My program will be consistently be checking these numbers to see if their value has been changed from the default.

For example lets say I have integers A,B,C. All these integers will be set to a default value at the start (lets say -1). Then as the program progresses, lets say A and B are set to 3 and 2 respectfully. Since C is still at the default value, the program can conclude than C hasn't been assigned a non-default value yet.

The problem arises when trying to find a unique default value. Since the values of the numbers can be set to anything, if the value its set to is identical to the default value, my program won't know if a float still has the default value or its true value is just identical to the default value.

I considered NULL as a default value, but NULL is equal to 0 in C++, leading to the same problem!

I could create a whole object consisting of an bool and a float as members, where the bool indicates whether the float has been assigned its own value yet or not. This however seems like an overkill. Is there a default value I can set my floats to such that the value isn't identical to any other value? (Examples include infinity or i)

I am asking for C/C++ solutions.

like image 676
fdh Avatar asked Dec 03 '22 03:12

fdh


2 Answers

I could create a whole object consisting of an bool and a integer as members, where the bool indicates whether the number has been assigned its own value yet or not. This however seems like an overkill.

What you described is called a "nullable type" in .NET. A C++ implementation is boost::optional:

boost::optional<int> A;

if (A)
  do_something(*A);
like image 123
kol Avatar answered Dec 21 '22 19:12

kol


On a two's complement machine there's an integer value that is less useful than the others: INT_MIN. You can't make a valid positive value by negating it. Since it's the least useful value in the integer range, it makes a good choice for a marker value. It also has an easily recognizable hex value, 0x80000000.

like image 41
Mark Ransom Avatar answered Dec 21 '22 18:12

Mark Ransom