0

The following works for g++

assert(nullptr == 0);

I need to know if there is any implicit type conversion that is happening. From what I know, nullptr can be compared with pointers only and not with integers, and also that it is more type-safe. Then why the comparison with integer works?

1 Answer 1

2

Then why the comparison with integer works?

Because, in most implementations, the nullptr is a 0 machine address. In other words (intptr_t)nullptr is 0. This is the case on Linux/x86-64 for example. Check by inspecting the generated assembler code obtained with g++ -S -O2 -fverbose-asm

I even believe that this is guaranteed by the C++ standard (read e.g. n3337)

However, if you compile your code with a recent GCC as gcc -Wall -Wextra you could get a warning.

Read also assert(3). In some cases (with NDEBUG) it is expanded to a no-op at compilation time.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.