java - C++ 中的 NULL 和 Java 中的 null 有什么区别?

标签 java c++ null

我一直试图弄清楚为什么 C++ 让我疯狂地键入 NULL。前几天它突然袭击了我;多年来,我一直在用 Java 输入 null(小写)。现在突然间我在用 C++ 编程,而那一小块肌肉内存让我发疯了。

Wikiperipatetic 将 C++ NULL 定义为 stddef 的一部分:

A macro that expands to a null pointer constant. It may be defined as ((void*)0), 0 or 0L depending on the compiler and the language.

Sun 的文档告诉我关于 Java 的“空文字”:

The null type has one value, the null reference, represented by the literal null, which is formed from ASCII characters. A null literal is always of the null type.

所以这一切都很好。我知道空指针引用是什么,感谢您的编译器注释。现在我对 Java 中文字的概念有点模糊,所以我继续阅读......

A literal is the source code representation of a fixed value; literals are represented directly in your code without requiring computation.

There's also a special null literal that can be used as a value for any reference type. null may be assigned to any variable, except variables of primitive types. There's little you can do with a null value beyond testing for its presence. Therefore, null is often used in programs as a marker to indicate that some object is unavailable.

好的,我想我现在明白了。在 C++ 中,NULL 是一个宏,它在编译时计算为空指针常量。在 Java 中,null 是一个固定值,也可以分配任何非原始值;非常适合在方便的 if 语句 中进行测试。

Java 没有指针,所以我可以理解为什么它们将 null 保留为一个简单的值,而不是任何花哨的值。 但是为什么java决定将所有大写的NULL改为null

此外,我这里有什么遗漏吗?

最佳答案

  • NULL 是一个预处理指令标识符,按照惯例,应该全部大写。

  • null 是一个 language litteral 表示一个常量值,并且按照惯例应该都更低(就像 true)。

关于java - C++ 中的 NULL 和 Java 中的 null 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2960193/

相关文章:

java - 带有 TestNG 插件和多个 eclipse 项目的 EclEmma 插件

c++ - 如何在不声明C/C++附加功能的情况下对代码进行重复数据删除?

c++ - 使用 GoogleTest 进行复合测试?

Mysql 返回 0 总和不为空

java - ImageView 空指针异常

java - 无法解析日期 2020 年 4 月 15 日 12 :14:17 AM to LocalDatetime

java - AWS Lambda - 如果我启动一个线程,当 Lambda 卡住/解冻时会发生什么?

c++ - 使用 Xcode 在 MacOS X 上安装 GMP

java空值检查语法差异

java - IClientConfig 参数有什么用?