为什么布尔变量的默认值往往为false? [英] Why does the default value of a boolean variable tend to be false?

查看:440
本文介绍了为什么布尔变量的默认值往往为false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,C#,VB,Java和JavaScript中的布尔变量的默认值为 false (或者可能是false为false)在JavaScript的情况下更准确),我相信还有很多其他语言是这种情况。

As far as I'm aware, the default value of a boolean variable in C#, VB, Java and JavaScript is false (or perhaps "behaves like false" is more accurate in the case of JavaScript) and I'm sure there are many other languages in which this is the case.

我想知道为什么会这样?为什么语言设计师为默认选择 false ?对于数值,我可以看到零是一个合理的选择,但是我看不到 false true

I'm wondering why this is? Why do language designers pick false for the default? For numerical values, I can see that zero is a logical choice, but I don't see that false is any more a natural state than true.

除此之外,是否有任何默认为true的语言?

And as an aside, are there any languages in which the default is true?

推荐答案

从语义的角度来看,布尔值表示条件或状态。许多语言假设,如果没有初始化,条件不满足(或这种状态是空的,或任何)。它像旗子一样。另一方面考虑它。如果布尔值的默认值为true,则该语言的语义将告诉您最初满足任何条件,这是不合逻辑的。

From the semantic point of view, boolean values represent a condition or a state. Many languages assume, if not initialized, that the condition is not met (or such state is empty, or whatever). It serves like a flag. Think about it on the other way around. If the default value for a boolean is true, then the semantics of that language would tell you that any condition is initially satisfied, which is illogical.

从实际的角度来看,编程语言通常在内部将布尔值存储为一个位(0为false,1为真),因此数字类型的相同规则适用在这种情况下,可以使用布尔值。

From the practical point of view, programming languages often internally store boolean values as a bit (0 for false, 1 for true), so the same rules for numeric types apply to booleans in this case.

布尔实例变量的Java的默认值始终为false,但不适用于局部变量,因此需要对其进行初始化。

Java's default value for boolean instance variables is always false, but that doesn't apply for local variables, you're required to initialize it.

这篇关于为什么布尔变量的默认值往往为false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆