Avatar ·

What is null/nil in C++ and how to work with it?

Question: What is null/nil in C++ and how to work with it?

Hello colleagues! I'm switching to C++ after Python and Java and can't quite understand the concept of null/nil in this language. Python has None, Java has null, but in C++ I encounter nullptr, NULL, and just 0. Are they the same thing? When should I use which?

I tried writing this code:

#include <iostream>\n\nvoid foo(int* ptr) {\n    if (ptr == NULL) {\n        std::cout << "Pointer is NULL" << std::endl;\n    }\n}\n\nint main() {\n    int* p = nullptr;\n    foo(p);\n    return 0;\n}

The code compiles, but I'm not sure if this is correct. I've also heard about std::optional — is that a completely different thing? Or is it a modern replacement for null? I expect a clear explanation: which of these