Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store some kind of "null" in C++ double or int variable?

Tags:

c++

null

c++11

I have a class that looks like this

struct A {
     double a1;
     int b1;
     double a2;
     int b2;
};

I have to read off of a file values for a1, b1, a2, and b2. Most of the time all four numbers are on the file, but sometimes there are only two numbers.

When there are two numbers, I want to store the values in a1, and b1 and I want to store "nothing" in a2 and b2. If a2 and b2 were pointers, I could just assign them to be nullptr, but they are not pointers.

Is there something I can store in double and int variables to indicate that 'nothing' is stored?

I know Boost.Optional is available, but I'm trying to avoid that library.

like image 492
jlconlin Avatar asked Aug 28 '14 17:08

jlconlin


People also ask

How do you store null in int?

You can insert NULL value into an int column with a condition i.e. the column must not have NOT NULL constraints. The syntax is as follows. INSERT INTO yourTableName(yourColumnName) values(NULL);

Can an int variable be null in C?

You cannot set the value of an integer to null. You can only set a pointer to null. So, you can set an integer pointer to null.

Can a double value be null?

Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.

Can a variable be null in C?

In C programming language a Null pointer is a pointer which is a variable with the value assigned as zero or having an address pointing to nothing. So we use keyword NULL to assign a variable to be a null pointer in C it is predefined macro.


2 Answers

You could assign NAN to the double a2, which would also indicate that the int b2 is invalid.

This page for NAN usage.

like image 145
jonas25007 Avatar answered Oct 10 '22 14:10

jonas25007


You cannot. I can think of two alternative ways:

  1. use int *; or
  2. Use a value that for sure invalid in your context. For example, if it can never be negative, then use -1 to indicate null. But I still prefer the first way, since its correctness is not depended on requirement or context.
like image 30
Peter Pei Guo Avatar answered Oct 10 '22 13:10

Peter Pei Guo