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

本文是小编为大家收集整理的关于为什么布尔变量的默认值往往是假的?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

据我所知,C#、VB、Java 和 JavaScript 中布尔变量的默认值为 false(或者在 JavaScript 的情况下"表现得像假"更准确),我我敢肯定还有很多其他语言都是这种情况.

我想知道这是为什么?为什么语言设计者选择 false 作为默认值?对于数值,我可以看到零是一个合乎逻辑的选择,但我不认为 false 比 true 更自然.

顺便说一句,有没有默认为 true 的语言?

推荐答案

从语义上看,布尔值代表一个条件或状态.许多语言假设,如果没有初始化,条件不满足(或者这种状态是空的,或者其他什么).它就像一面旗帜.反过来想想.如果布尔值的默认值为 true,那么该语言的语义会告诉您最初满足任何条件,这是不合逻辑的.

从实用的角度来看,编程语言通常在内部将布尔值存储为位(0 表示假,1 表示真),因此在这种情况下,数字类型的相同规则适用于布尔值.

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

本文地址:https://www.itbaoku.cn/post/627332.html

问题描述

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.

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.

And as an aside, are there any languages in which the default is 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.

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's default value for boolean instance variables is always false, but that doesn't apply for local variables, you're required to initialize it.