Can ‘\0’ and NULL be used interchangeably?

Could anyone provide an example that NULL and \0 cannot be interchanged?

The difference between NULL and '\0' may affect overload resolution.

Example (check it on Coliru):

#include <iostream>

// The overloaded function under question can be a constructor or 
// an overloaded operator, which would make this example less silly
void foo(char)   { std::cout << "foo(char)"  << std::endl; }
void foo(int)    { std::cout << "foo(int)"   << std::endl; }
void foo(long)   { std::cout << "foo(long)"  << std::endl; }
void foo(void*)  { std::cout << "foo(void*)" << std::endl; }

int main()
{
    foo('\0'); // this will definitely call foo(char)
    foo(NULL); // this, most probably, will not call foo(char)
}

Note that the gcc compiler used at Coliru defines NULL as 0L, which for this example means that foo(NULL) resolves to foo(long) rather than to foo(void*). This answer discusses that aspect in detail.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)