温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

NULL与""空字符串的区别

发布时间:2020-07-07 06:32:39 来源:网络 阅读:1335 作者:XDATAPLUS 栏目:编程语言

""空字符串,会创建一个对象,分配内存空间

NULL,不会创建对象,不会分配内存空间,意思是不存在的


#include <iostream>
using namespace std;

int main()
{
        std::string strTemp;

        if( strTemp.empty() )
        {
                cout<<"is empty "<<endl;
        }
        else
        {
                cout<<"is not empty"<<endl;
        }

        strTemp = "";

        if( strTemp.empty() )
        {
                cout<<"is empty"<<endl;
        }
        else
        {
                cout<<"is not empty"<<endl;
        }

        if( strTemp == "" )
        {
                cout<<"is empty"<<endl;
        }
        else
        {
                cout<<"is not empty"<<endl;
        }

        /*
        if( strTemp == NULL )
        {
                cout<<"is empty"<<endl;
        }
        else
        {
                cout<<"is not empty"<<endl;
        }
        */

        return 0;
}

在以下代码最后,用NULL与字符类型进行比较,会直接导致编译错误!

test.cpp:37:17: error: no match for ‘operator==’ in ‘strTemp == 0’

从编译的错误提示看:NULL为数值0


#include <iostream>
using namespace std;

int main()
{
        if( NULL == 0 )
        {
                cout<<"NULL is number 0"<<endl;
        }
        else
        {
                cout<<"NULL is not number 0"<<endl;
        }

        int nNum;
        cout<<"nNUm = "<<nNum<<endl;

        nNum = NULL;
        cout<<"nNUm = "<<nNum<<endl;

        cout<<static_cast<void*>(NULL)<<endl;

        return 0;
}

从这段代码,进一步验证了,NULL对就的值为数值0,地址为空

注意:将NULL赋值为int变量时会报警告

NULL.cpp:18:9: warning: converting to non-pointer type ‘int’ from NULL [-Wconversion-null]

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI