What is the difference among NULL, '\0' and ""?

I am confused that what is the difference among NULL, '\0' and ""?

I wrote a short program 1 to test int and char types:

#include <iostream>
#include <string>

using namespace std;

int main()
{
int a=NULL, b=0;
char ch1=NULL, ch2='\0';

if(a==b)
cout<<"a=b"<<endl;
else
cout<<&a<<endl;

if(ch1==ch2)
cout<<"ch1=ch2"<<endl;
else
cout<<&a<<endl;

return 0;
}

The result is a=b, ch1=ch2
Dose that mean NULL is same as 0 or '\0'?



And I wrote program 2 to test string type:

#include <iostream>
#include <string>

using namespace std;

int main()
{
string str1=NULL, str2="";

if(str1==str2)
cout<<"str1=str2"<<endl;
else
cout<<&str1<<endl;

return 0;
}

There's an error window pops up.What does that mean?

Thanks.
NULL is a macro for 0, it is used for pointers.
'\0' is 0 but it is a char, not an int
"" is a character sequence containing only a '\0' (Notice that a character sequence is not a character)

So NULL is exactly the same as 0, '\0' has the same value but a different type.

You can't initialize a string with an integral value.
Last edited on
Bazzy

Understood, thanks.
NULL and 0 are not exactly the same.
NULL should be defined like this: #define NULL 0 .
Where the difference between them?
The compiler differentiates between NULL and 0 on occasion, but they are the same when you get down to it. Storing NULL in a sequence of bits makes them all 0. Storing 0 in a sequence of bits makes them all 0 as well.

NULL == 000000... == 0

I think a good way of looking at it is: NULL is for pointers, 0 (or 0.0) is for numbers, and '\0' is for text (characters and strings). Otherwise they're exactly the same :)
Topic archived. No new replies allowed.