No, references cannot be NULL in C++.1

Possible solutions include:

  • using a pointer instead of a reference.
  • having a dummy Object instance that can be used to indicate "no object".

[1] From the C++11 standard:

[dcl.ref] [...] a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior.

Answer from Oliver Charlesworth on Stack Overflow
🌐
Reddit
reddit.com › r/cpp_questions › when do we need to initialize a pointer to null?
r/cpp_questions on Reddit: When do we need to initialize a pointer to NULL?
December 28, 2017 -

In my textbook (Starting Out with Early Objects, Gaddis, Tony 9th Ed), in a chapter about c-strings and strings it gives this code example:

char name[] = "John Q. Public ";

char *p;

p = name;

cout << p << endl;

p = "Jane Doe";

cout << p << endl;

and then about 1 page later it goes on to say: A common mistake when using pointers to char as C-strings is using the pointer when it does not point to a properly allocated C-string . For example, the code

char *pname;

cout << "Enter your name: ";

cin >> pname;

what's wrong with the second set of code? When do we need to initialize a pointer to null and when can we skip it?

Discussions

c - is it necessary to call pointer = NULL when initializing? - Stack Overflow
As pointers, just like other variables will hold garbage value unless it is initialized. ... Save this answer. ... Show activity on this post. No, you don't have to set it to NULL, but some consider it good practice as it gives a new pointer a value that makes it explicit it's not pointing ... More on stackoverflow.com
🌐 stackoverflow.com
c++ - How to initialize a pointer to null - Stack Overflow
I think T a{}; is a more terse way to value-initialize anything. ... @πάνταῥεῖ: No it won't, since that wouldn't compile. NULL must be nullptr or a zero-valued integer literal, to be convertible to any pointer type. More on stackoverflow.com
🌐 stackoverflow.com
c - How to initialize a struct to null? - Stack Overflow
I have a struct that contains two other structs of the same type, and I want to initialize it to have both NULL to start. How do I do that? I've tried the below, but get compiler warnings with gc... More on stackoverflow.com
🌐 stackoverflow.com
Why is it possible to declare an uninitialized reference to a variable in the header file (and is it used/considered good practice?)
All references must be initialized at the point of instantiation. For the standalone int & i;, that's attempting to instantiate an i at that point, and thus must be initialized there as well. In your second case of Api & api;, that's not attempting to instantiate it as it is merely a member of the class. That means it will get instantiated during the construction of an instance of that class. Which you can see in the definition of the constructor, it gets passed in a reference, which it uses to initialize the api member variable. More on reddit.com
🌐 r/cpp_questions
13
29
June 1, 2021
Top answer
1 of 8
119

Is it possible to initialize a C pointer to NULL?

TL;DR Yes, very much.


The actual claim made on the guide reads like

On the other hand, if you use just the single initial assignment, int *my_int_ptr = 2;, the program will try to fill the contents of the memory location pointed to by my_int_ptr with the value 2. Since my_int_ptr is filled with garbage, it can be any address. [...]

Well, they are wrong, you are right.

For the statement, (ignoring, for now, the fact that pointer to integer conversion is an implementation-defined behaviour)

int * my_int_ptr = 2;

my_int_ptr is a variable (of type pointer to int), it has an address of its own (type: address of pointer to integer), you are storing a value of 2 into that address.

Now, my_int_ptr, being a pointer type, we can say, it points to the value of "type" at the memory location pointed by the value held in my_int_ptr. So, you are essentially assigning the value of the pointer variable, not the value of the memory location pointed to by the pointer.

So, for conclusion

 char *x=NULL;

initializes the pointer variable x to NULL, not the value at the memory address pointed to by the pointer.

This is the same as

 char *x;
 x = NULL;    

Expansion:

Now, being strictly conforming, a statement like

 int * my_int_ptr = 2;

is illegal, as it involves constraint violation. To be clear,

  • my_int_ptr is a pointer variable, type int *
  • an integer constant, 2 has type int, by definition.

and they are not "compatible" types, so this initialization is invalid because it's violating the rules of simple assignment, mentioned in chapter §6.5.16.1/P1, described in Lundin's answer.

In case anyone's interested how initialization is linked to simple assignment constraints, quoting C11, chapter §6.7.9, P11

The initializer for a scalar shall be a single expression, optionally enclosed in braces. The initial value of the object is that of the expression (after conversion); the same type constraints and conversions as for simple assignment apply, taking the type of the scalar to be the unqualified version of its declared type.

2 of 8
54

The tutorial is wrong. In ISO C, int *my_int_ptr = 2; is an error. In GNU C, it means the same as int *my_int_ptr = (int *)2; . This converts the integer 2 to a memory address, in some fashion as determined by the compiler.

It does not attempt to store anything in the location addressed by that address (if any). If you went on to write *my_int_ptr = 5;, then it would try to store the number 5 in the location addressed by that address.

🌐
Quora
quora.com › Is-there-a-difference-between-initializing-a-pointer-to-NULL-or-initializing-it-to-zero-in-C
Is there a difference between initializing a pointer to NULL or initializing it to zero in C? - Quora
Answer (1 of 10): Is there a difference between initializing a pointer to NULL or initializing it to zero in C? A datatype consists of: possible values, possible operations and — for engineers — storage size. NULL is a possible value of a variable of type pointer.
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › can-c-reference-member-be-declared-without-being-initialized-with-declaration
Can C++ reference member be declared without being initialized with declaration? - GeeksforGeeks
April 26, 2021 - To many readers, this might sound the same thing, i.e. class_type *var = NULL; *var = &some_work; is same as class_type *var = &some_work; But in actual, it is not. When the declaration and initialization are done at the same step, the compiler calls the copy constructor whereas if done in ...
🌐
Quora
quora.com › Why-are-pointers-not-initialized-to-null-by-default-in-C-when-declared-If-they-are-uninitialized-how-can-we-know-whether-they-point-to-a-valid-memory-address-or-not
Why are pointers not initialized to null by default in C++ when declared? If they are uninitialized, how can we know whether they point to a valid memory address or not? - Quora
Answer: Initialization takes time, and C++ (like C) has a philosophy of not paying for unused features, so initialization is up to the developer. Static variables are an exception, and static pointers are initialized to nullptr by default. Compile-time initialization doesn't cost anything as the...
🌐
Cppreference
en.cppreference.com › w › cpp › language › reference_initialization.html
Reference initialization - cppreference.com
May 20, 2024 - In all cases where the reference-compatible relationship of two types is used to establish the validity of a reference binding and the standard conversion sequence would be ill-formed, a program that necessitates such a binding is ill-formed. ... The reference to be initialized is an lvalue reference.
🌐
IBM
ibm.com › docs › en › zos › 2.4.0
Initialization of references (C++ only)
The page you requested cannot be displayed (HTTP response code 403)
Find elsewhere
🌐
Learn C++
learncpp.com › cpp-tutorial › null-pointers
12.8 — Null pointers – Learn C++
August 12, 2015 - Use nullptr when you need a null pointer literal for initialization, assignment, or passing a null pointer to a function. Dereferencing a null pointer results in undefined behavior · Much like dereferencing a dangling (or wild) pointer leads to undefined behavior, dereferencing a null pointer ...
🌐
Code with C
codewithc.com › code with c › c++ tutorial › c++ can a reference be null? exploring reference semantics
C++ Can A Reference Be Null? Exploring Reference Semantics - Code With C
January 1, 2024 - They provide a way to access an existing variable by another name, and they are an integral part of C++ programming. Unlike pointers, references cannot be null, cannot be reseated after initialization, and they must be initialized when declared.
🌐
Unstop
unstop.com › home › blog › null pointer in c | a detailed explanation with examples
Null Pointer In C | A Detailed Explanation With Examples
May 3, 2024 - If a pointer variable is not assigned a valid memory address, it may be initialized to null to indicate that it is not currently pointing to anything. Null and void are related concepts in programming but are not the same. Null: In programming, null typically refers to a special value that represents the absence of a valid or meaningful object or reference.
🌐
Reddit
reddit.com › r/cpp_questions › why is it possible to declare an uninitialized reference to a variable in the header file (and is it used/considered good practice?)
r/cpp_questions on Reddit: Why is it possible to declare an uninitialized reference to a variable in the header file (and is it used/considered good practice?)
June 1, 2021 -

Hi everyone,

I have an unusual question because I only saw people at work doing this and it confused me since I could not find anything about it on the internet.

So I have a basic understanding of c++ and as far as I know, c++ does not allow me to create a reference without initializing it. Meaning I can create an uninitialized variable if I want to but if I want a reference then I must give it a value to reference to, which makes sense.

int i; // ok

int& i; // error

int i = 0 // ok

int& j = i // ok

int i = 0 // ok

int& j = i // ok

Now I saw people at work doing exactly that and it confused me because the project builds and works successfully! Here is an example. Let's say we have a class A that has an Api member like the following

// header file

class A {
A() = default;
A(Api &api);

private:
Api& api // does it make a difference if I declared the api attribute not as a reference?
// (like this: Api api and let the rest as it is
}

// cpp file

A::A(Api &api): api{api}

This is what confused me. The api private member/attribute is declared as a reference but it is not initialized so what does it reference exactly? As far as I know, references cannot be Null and must have a value so how can this declaration be possible?

My guess is that it is legit because the declaration is in the header file and the api member will be directly initialized in the constructor so eventually it will refer to something when the program runs and hence the compiler accept this. Am I right?

Can someone explain this to me and even better maybe tell me if this writing has any benefits or if they are using it. I tried to search on the internet about this but I didn't find any c++ code that uses this style of declaring references in the header file.

Top answer
1 of 2
34
All references must be initialized at the point of instantiation. For the standalone int & i;, that's attempting to instantiate an i at that point, and thus must be initialized there as well. In your second case of Api & api;, that's not attempting to instantiate it as it is merely a member of the class. That means it will get instantiated during the construction of an instance of that class. Which you can see in the definition of the constructor, it gets passed in a reference, which it uses to initialize the api member variable.
2 of 2
2
Generally the guidelines we use at work and I also use on my personal projects. Is it a primitive? Then we initialize it in the header. int, float, bool, get appropriate values(e.g. 0, false, or whatever), a raw pointer* get's assigned to nullptr, and lastly, we inconsistently initialize enums to default values if there is an appropriate default value (e.g. unknown). We would never have type& name; in our class members variables. But if we did, it'd probably point to nullptr. And I don't think anyone should. (Not to be confused with parameters of functions/methods, which are a different convo) else Things like std::string, custom types, smart pointers, are just left as-is. std::string m_someString; MyClass m_myClass; std::shared_ptr m_someClass; We also have compiler warning/error enabled such that will alert us of any members not initialized in constructor or in header. Example: // MyClass.h class MyClass { ... int m_count = 0; bool m_enabled = false; std::string m_message; std::shared_ptr m_otherClass; void* m_opaqueData = nullptr; float m_timeElapsed = 0.0f; EMode m_mode = EMode::Unknown; }
🌐
Cplusplus
cplusplus.com › forum › general › 46508
How to declare a varibale as null - C++ Forum
The empty string. I don't know about the CString datatype but when comparing strings you don't really compare NULL or not you compare to empty. ... If you want to store a NULL value, you need to use pointers. There is no such thing as a NULL object (or reference) in C++.
🌐
IBM
ibm.com › docs › SSLTBW_2.2.0 › com.ibm.zos.v2r2.cbclx01 › cplr116.htm
IBM Documentation
December 6, 2018 - Get assistance for the IBM products, services and software you own · Provides fixes and updates for your system's software, hardware, and operating system
🌐
Sololearn
sololearn.com › en › Discuss › 1370110 › can-someone-please-explain-why-in-what-situation-a-pointer-is-initialized-with-null
Can someone please explain why (in what situation) a pointer is initialized with NULL? | Sololearn: Learn to code for FREE!
June 26, 2018 - Implemented as #define NULL nullptr ~example~ int *ptr1 = NULL; int *ptr2 = nullptr; ~case in point~ Initialization of a head and tail nodes in a singly linked list. struct Node { int data; Node *next; }; class List { public: List() { head = ...
🌐
Tutorialspoint
tutorialspoint.com › cplusplus › cpp_references.htm
C++ References
Once a reference is initialized ... but three major differences between references and pointers are − · You cannot have NULL references....
🌐
Wikipedia
en.wikipedia.org › wiki › Reference_(C++)
Reference (C++) - Wikipedia
June 1, 2026 - Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created. Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers. References cannot be null, whereas pointers ...