Why does the default value of a boolean variable tend to be false? [closed]

冷暖自知 提交于 2019-12-18 08:32:46

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/14157180/why-does-the-default-value-of-a-boolean-variable-tend-to-be-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!