Integer overflow: Difference between revisions
Updated Kotlin example since Kotlin has unsigned types.
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
(Updated Kotlin example since Kotlin has unsigned types.) |
||
Line 1,625:
A Kotlin program does <b>not</b> recognize a signed integer overflow and the program <b>continues with wrong results</b>.
<syntaxhighlight lang="
// The Kotlin compiler can detect expressions of signed constant integers that will overflow.
// It cannot detect unsigned integer overflow, however.
@Suppress("INTEGER_OVERFLOW")
fun main(
println("*** Signed 32 bit integers ***\n")
println(-(-2147483647 - 1))
Line 1,647 ⟶ 1,643:
println(3037000500 * 3037000500)
println((-9223372036854775807 - 1) / -1)
println("\n*** Unsigned 32 bit integers ***\n")
// println(-4294967295U) // this is a compiler error since unsigned integers have no negation operator
// println(
println((
println(
println(2147483647U - 4294967295U)
println(65537U * 65537U)
println("\n*** Unsigned 64 bit integers ***\n")
println(0U - 18446744073709551615U) // we cannot convert from a signed type here (since none big enough exists) and have to use subtraction
println(10000000000000000000U + 10000000000000000000U)
println(9223372036854775807U - 18446744073709551615U)
println(4294967296U * 4294967296U)
}</syntaxhighlight>
Line 1,679 ⟶ 1,681:
2147483648
131073
*** Unsigned 64 bit integers ***
1
1553255926290448384
9223372036854775808
0
</pre>
|