[Gambas-user] Wrong error message

Benoît Minisini gambas at ...1...
Tue May 4 20:00:10 CEST 2010


> 
> Ok, now I understand the two code snippets above. The net result should
> be an integer having value 9876543210. Apart from the fact that a simple
> assignment does the same work, which leads me to think that Jussi wanted
> something else, I am still not convinced about the casting (or, better,
> conversion) while writing to variables.
> 
> I feel something weird in using an integer variable as if it was a
> string, and the above snippet does that.
> 
> I wrote the same code and tried it - "wanted integer got string
> instead". Then I traced the code, and discovered that the conversion
> fails because an overflow, but the resulting error says something else
> (I can understand why).
> 
> Well, what to say? I don't like the automatic conversion while writing,
> but I am not sure. The more the language does things by its own, the
> more you can get confused - anyway we don't want a stupid language you
> must say everything to, right?. The routine I tested is:
> 
> PUBLIC SUB Form_Open()
>   DIM i, k AS Integer
> 
>   k = 9876543210
>   k = 0
> 
>   FOR i = 9 TO 0 STEP -1
>     ' k &= i
>     PRINT "k="; k, "i="; i
>     k = CInt(CStr(k) & CStr(i))
>   NEXT
> END
> 
> The first assignment "k = 9876543210" is silently accepted by both the
> compiler and the interpreter, and is wrong. 

Yep, it is more vicious there. The 9876543210 is too large for an Integer, so 
the compiler uses a Long constant instead. Then the Long value is assigned to 
the 'k' Integer variable, and so is automatically converted to an integer. 
Alas, overflow during arithmetic conversion is not detected by the C language 
(whereas internally the CPU can), and doing that detection by code will slow 
down things *a lot*. So the value is just truncated: you can print 'k' just 
after the assignment to get the value.

Regards,

-- 
Benoît Minisini




More information about the User mailing list