How can you safely compare a pointer to detect a null reference?

Enhance your programming skills with the RECF Programming Test. Features flashcards and multiple choice questions with hints and explanations. Prepare for success!

Multiple Choice

How can you safely compare a pointer to detect a null reference?

Explanation:
The key idea is checking whether a pointer is null by comparing it to NULL (or nullptr) with the equality operator. This tells you if the pointer doesn’t currently point to a valid object. Using the assignment operator inside the condition would set the pointer to NULL, which is a bug and can wipe out your pointer. Dereferencing the pointer in the test, as in testing *ptr, is unsafe if the pointer could be null and can lead to a crash. Checking for non-null with ptr != NULL would take the opposite branch and miss the case where the pointer is null. So the safe, correct approach is to test whether the pointer equals NULL (or nullptr) and handle that case accordingly. In modern C++, prefer nullptr to NULL.

The key idea is checking whether a pointer is null by comparing it to NULL (or nullptr) with the equality operator. This tells you if the pointer doesn’t currently point to a valid object. Using the assignment operator inside the condition would set the pointer to NULL, which is a bug and can wipe out your pointer. Dereferencing the pointer in the test, as in testing *ptr, is unsafe if the pointer could be null and can lead to a crash. Checking for non-null with ptr != NULL would take the opposite branch and miss the case where the pointer is null. So the safe, correct approach is to test whether the pointer equals NULL (or nullptr) and handle that case accordingly. In modern C++, prefer nullptr to NULL.

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy