In which languages is `if (x)` a legal test for nonzero value?
I'm curious how universal the language paradigm is of allowing plain if (x) ...
to check for nonzero value (on an integer variable, at least)?
(as opposed to explicitly requiring an operator: if (x != 0)
)
Motivated by this question which was tagged as language-agnostic, but that's strictly not even 100% correct for languages currently in common use, although it's close-enough. Is this always true of weakly-typed languages?
(Assume that x has been defined so we don't need to worry about that or exceptions. x may not necessarily have been initialized but consider that a separate case.)
Here is a summary:
C/C++, PERL, Python, PHP, Ruby, BASIC: Yes
C#, Java; Pascal, Modula-2 &开发者_如何学编程 other descendants of Pascal: illegal - must be Boolean
Fortran: Illegal syntax - must be Boolean
LISP: All integers considered true, nil considered false.
bash: Legal, but beware 0 signifies command success and nonzero signifies failure
There are plenty of other languages that don't use this idiom.
For example, in various Lisps (including Clojure) nil is considered a false value but all integers are considered true:
(if nil "True" "False")
=> "False"
(if 0 "True" "False")
=> "True"
The condition must be Boolean in: C#, Java; Pascal, Modula-2 & other descendants of Pascal
The condition can be integer in: Basic (lacks Boolean)
This made me think of Ruby.
a = 0
b = 5
if a
p "true!"
end
if b
p "true!"
end
Will both print "true!". Then there's that sweet .zero?
method:
a.zero?
=> true
b.zero?
=> false
精彩评论