Daniel McIntosh
Daniel McIntosh

Reputation: 575

Are there any differences between if (!x) and if (x == nullptr)?

Ignoring user-defined operator overloads, are there any cases where if (!x) would behave differently from if (x == nullptr). Or, conversely are there any cases where if(x) would behave differently from if (x != nullptr).

e.g. Are there any types in the standard library for which !x would behave differently from x == nullptr.

Note: I'm aware this is very similar to many other questions on SO, but believe it still warrants it's own question. I've given my justification for why here: Are questions about NULL sufficiently different from questions about nullptr?

Also, on that meta-post, L. F. pointed out that std::optional<T*> is one such case. However, I'm interested to know whether there are any others, especially with primitive and/or pointer types.

Upvotes: 2

Views: 171

Answers (1)

Jarod42
Jarod42

Reputation: 217573

They differ for most primitive types.

boolean for example:

!true is valid whereas true == nullptr is ill formed.

Upvotes: 6

Related Questions