why c++ support this
int main()
{
if(NULL)
std::cout << "compile";
if(5)
std::cout << "compile";
if(4.78)
std::cout << "compile";
if("lala")
std::cout << "compile";
}
and in java
public class Test {
public static void main(String[] args) {
if(null) System.out.println("true");
}
}
Error:(5, 12) java: incompatible types: cannot be converted to boolean
from https://en.wikipedia.org/wiki/Java_bytecode_instruction_listings
java and c++ it's just an example
Lua and js also support this
and kotlin not
I am trying to understand why one language support null check by default and the other doesn't?
They are different languages, and different languages can have different semantics! In C or C++, NULL
actually just is a pre-processor macro, either defined to 0
or to an expression that produces a null pointer (((void*)0)
). Additionally, C++ (but not C!) comes with a null pointer keyword (nullptr
, since C++11) which nowadays should be preferred over the macro or the integer literal 0
.
Then in C and in C++, you can test numbers (integral or floating point) and pointers directly. Anything that compares equal to 0 is accepted as false
, anything else is accepted as true
. For instance:
int n = 0;
int* p = nullptr; // C++ only, 0 or NULL in C
double d = 0.0;
if(n) { }
if(p) { }
if(d) { }
// all of these are equivalent to if(x != 0), x being n, p or d
Alike, you can test literals as well (all below actually never enter the if branch):
if(false) { }
if(0) { }
if(nullptr) { }
Java, in contrast, only accepts true boolean values. So what is implicit in C or C++ must be written explicitly in Java (and possibly Lua, but I'm not familiar with):
if(someBoolean) { } // fine, as boolean already
if(someInt != 0) { }
if(someReference != null) { }
Side note: There are yet some other languages that use C/C++ semantics as well, for instance Python or JavaScript.