用指针写条件的几种方式的区别

Differences among several ways of writing conditions with pointers

本文关键字:几种 方式 区别 指针 条件      更新时间:2023-10-16

我想知道是否有人可以总结一下写一个涉及指针的条件语句的方法之间的区别:

if(p)
if(p != 0)
if(p != NULL)

我经常对以下情况感到困惑(肯定有更多,请补充你的情况)何时使用which:

static char *p1;
char *p2 = new char();
const char *p3 = "hello"; /*then I repeatedly do p3++*/
char *p4 = 0;
char *p5 = NULL;

编辑

另外,我想知道,对于char *p,我们是否有while(*p)while(*p!=0),可能相当于while(p)while(p!=0)while(p!=NULL)while(*p!='')(或任何其他?)在while循环内的一些p++之后?

if(p)

在此上下文中,p被转换为bool,这实际上与p != 0相同。

if(p!=0)

这是检查空指针的显式方法,与上一个相同。

if(p != NULL)

与此不同的是NULL是一个宏;在C中定义为(void*)0,而在c++中定义为0。同样,它的检查与前两个表达式相同。

基本上,它们都做同样的事情(除了NULL宏没有被定义或被重新定义为其他东西)。我倾向于使用p != 0,因为它与p相同,但它是明确声明的。使用NULL的版本需要包含stddefcstddef,这通常不是问题。

在c++ 11中有一种新的方法来检查空指针:nullptr,这是一个新的关键字。如果可用,这将是理想的选择,因为它清楚地说明p是一个指针:

if( p != nullptr )

这些都是检查p是否不是0的方法;它们做同样的事情:

if(p)            // Short and simple.
if(p != 0)       // Easier to understand.
if(p != NULL)    // POINTERS ONLY.

在c++ 11中,您可以使用这种"更安全"的方式来检查指针是否为NULL:

if(p != nullptr)

当你想创建一个'动态分配'的char s数组时,你可以这样做:

char *p2 = new char[4];
strcpy(p2, "abc");
// Don't forget to delete!
delete[] p2;
一个更好的选择是使用更安全的c++:
std::array<char, 256> p2 = {'b', 'b', 'c', 0};
p2[0] = 'a'; // "abc"

或:

std::string p2 = "bbc";
p2 = "abc";
p2[0] = 'c'; // "cbc"

p3设置为字符串"hello":

const char *p3 = "hello";

增加p3在内存中指向的位置:

// *p3 = 'h';
p3++;
// *p3 = 'e';
p3++;
// *p3 = 'l';
p3++;
// *p3 = 'l';

要理解你为什么这样做:

char *p4 = 0;
char *p5 = NULL;

查看这个问题:在free

之后将变量设置为NULL

我不会在c++中使用static char*,但这里有一个愚蠢的例子:

void sc(char *first = NULL)
{
    static char *p = NULL;
    if(p == NULL)
        p = &first;
    // p will never change (even when sc() ends) unless you set it to NULL again:
    // p = NULL;
}
char initial_value;
sc(&initial_value);
sc();
sc();
// ...