John Doe
John Doe

Reputation: 31

How to store variable as nothing

I have a class with unsigned chars inside.

There is the first instance of the class:

{
    unsigned char a = 5;
    unsigned char b = 243;
    unsigned char c = 0;
}

But there is an option some of these unsigned chars won't be filled.

Instance would look like this one:

{
    unsigned char a = 4;
    unsigned char b = 7;
    unsigned char c = <not_filled>;
}

I know there is the NULL defined as zero, so I cannot find out if it's zero or not_filled.

I know if I keep the variable undefined, it will be zero.

What should I do with this?

Upvotes: 1

Views: 80

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

std::optional is what you're looking for:

#include <optional>

struct MyStruct {
    std::optional<unsigned char> a = 4;
    std::optional<unsigned char> b = 7;
    std::optional<unsigned char> c = std::nullopt;
};

An example usage:

#include <iostream>
#include <optional>

struct MyStruct {
    std::optional<unsigned char> a = std::nullopt;
    std::optional<unsigned char> b = std::nullopt;
    std::optional<unsigned char> c = std::nullopt;
};

int main() {
    MyStruct ms{'a', 'b'};
    if (ms.a.has_value()) std::cout << *ms.a << '\n';
    if (ms.b.has_value()) std::cout << *ms.b << '\n';
    if (ms.c.has_value()) std::cout << *ms.c << '\n';
}

Upvotes: 3

Related Questions