vb6 - 为什么-1是在VB6中将True强制为整数的结果?

标签 vb6 language-design

在VB6中,将True强制为整数会产生值-1。

为什么会这样呢?这背后的原因是什么?

在大多数其他编程语言(C/C++,Java,Perl,Python等)中,当强制为整数时,true为1。在 bool 代数中,值1用于表示true/on。为什么VB6会有所不同?

我确实看到了某种优雅的对称性,因为按位不为-1(True)会产生0(False),反之亦然(因为-1的表示在two's complement中全为1),但是我不能想想这种身份的任何实际好处。

顺便说一句,我只是出于好奇而问-当我第一次学习VB6时,这让我感到很奇怪,从那时起,我一直在想。

最佳答案

您非常接近这个原因... Eric Lippert reveals the horrible, horrible truth:

What's going on is that VBScript is not logical. VBScript is bitwise. All the so-called logical operators work on numbers, not on Boolean values! Not, And, Or, XOr, Eqv and Imp all convert their arguments to four-byte integers, do the logical operation on each pair of bits in the integers, and return the result. If True is -1 and False is 0 then everything works out, because -1 has all its bits turned on and 0 has all its bits turned off.



(作为Chris Smith notes,很长一段时间以来对于各种BASIC都是如此……)

请注意,在VB.NET中,引入了逻辑运算符(即,仅对 bool 数据类型进行运算的运算符),但是如果输入整数类型,则现有运算符仍将愉快地执行按位运算。当我在C++和VB之间移动时,这经常使我感到沮丧。

关于vb6 - 为什么-1是在VB6中将True强制为整数的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3973672/

相关文章:

vb.net - 名称 'Printer' 未声明为 VB6 到 .NET

vb6 - 如何修复我的源代码绑定(bind)?

SQL Azure : Executing SQL directly; no cursor

C++ 迭代器被认为是有害的?

vb6 - 如何在 VB6 中读取 .zpl 数据矩阵中的可变长度应用程序标识符?

html - 使用visual basic登录和退出网站

exception-handling - 语言设计(异常(exception)): Why `try` ?

c# - 为什么在 C# 中 if 和委托(delegate)的范围是这样的

ruby - 需要帮助改进 Ruby DSL 以控制 Arduino 控制的饮料分配器(bar monkey)

kotlin - Dart "sound null-safety"与 Kotlin 空安全有何不同?