问指向数组的指针是真还是假是什么意思?

我对编程很陌生,一直在查看一些示例代码,我只想知道if(!pi)这段代码中的语句是什么意思。

// allocate and populate array
    int* pi = new int[N];
    if (!pi)
        return 1;
    for (int i = 0; i < N; i++)
        pi[i] = rand() % 100000;

回答

指针可以隐式转换为bool. 如果指针为空,则结果为false,否则为true。运算符!是逻辑非运算符。

在这种情况下,检查是多余的,因为new[]永远不会返回空指针,因此条件永远不会为真。

  • For illustration, GCC eliminates the check and the corresponding branch under optimizations: https://godbolt.org/z/7T4hfb.

以上是问指向数组的指针是真还是假是什么意思?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>