2

Goal

I want to know if there is a 'null' in C++, just like how there is None in Python or a nil in Ruby. I also want to know how you should use it.

Code

Here is my C++ code I made.

#include <iostream>

int main()
{
  bool value = _____;      // Are you supposed to use 'null' with a 'bool' type?
  std::cout << value;
}

Attemps

I tried replacing _____ with null, nil, Null, and Nil, but none of them worked! I even tried to replace _____ with none and None, but all I got was this error message (not complete error message):

main.cpp: In function 'int main()':
main.cpp:5:16: error: 'None' was not declared in this scope

The website Repl.it even suggested to change None into clone. Should I?

main.cpp:5:16: note: suggested alternative: 'clone'

So how do you have 'null' fit into a variable, but is there even a 'null' in C++?

  • 2
    There is no such thing for non-pointers. In this case, a `bool` can be `true` or `false`, *that's it*. – Borgleader Jan 26 '18 at 01:01
  • 3
    What are you trying to accomplish with this? This seems like an X, Y problem as it stands. – scohe001 Jan 26 '18 at 01:01
  • Booleans can have only two possible values: true (1), and false (0). – Mitch Wheat Jan 26 '18 at 01:01
  • A `bool` has just two possible values, represented by integers 0 and 1. You can define your own types that in addition can be "null". It's seldom a good idea. Or, OK, you can use `std::optional`. It's probably not a good idea for you to latch on to, but it's a technical possibility. – Cheers and hth. - Alf Jan 26 '18 at 01:02
  • [std::optional](http://en.cppreference.com/w/cpp/utility/optional). – O'Neil Jan 26 '18 at 01:04

2 Answers2

5

For something like a bool, you have exactly two possible values, true, or false. There is no third "lack of value."

The way Python (I can't speak for Ruby) does this "lack of value" is by not actually storing true or false under the surface, but rather storing the address of a location storing true or false. When you ask what the value is, it goes to that address and checks.

This way, if you want "lack of value," it simply changes the address it's storing to the null address. This allows for a pseudo "third possible value."

You can accomplish this in C++ by using a boolean pointer (ie: bool *b), but it's probably not a good idea. Depending on your situation there's almost definitely a better way to handle a "lack of value."

Alternatively, you could make an enum with three possible values ie:

enum valState { ISGOOD, ISBAD, ISNULL };

Which will allow you to do:

valState state = ISBAD;
if(state == ISNULL) { ...
scohe001
  • 15,110
  • 2
  • 31
  • 51
2

The only time you can use NULL or nullptr is with a pointer type. Most simple types and classes don't have any none-style value equivalent.

In C++17 you can use std::optional to wrap another type, but that's a distinct type and can't be used interchangeably with the base type.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622