gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:29:26 26 4
gpt4 key购买 nike

在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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com