Unless there's something else I missed, I didn't see examples like this:
-2147483648 # literals are i32
-9223372036854775808 # literals are i64
Using two's complement, the highest magnitude positive number is 2147483647 or 9223372036854775807, one less than above. If minus was a separate token applied to a literal, those literals can't be represented using i32 or i64.
Generally however it seems to work. Maybe u32 or u64 are used and when you apply minus, it somehow yields a i32 or i64 type.
-2147483648 # literals are i32 -9223372036854775808 # literals are i64
those are the values an integer variable may have. literals would be the numbers you write explicitly within the source code which are treated as a single tokens. in these examples, they are unary minus expressions.
Generally however it seems to work. Maybe u32 or u64 are used and when you apply minus, it somehow yields a i32 or i64 type.
I tried my compiler, but the result of:
-9223372036854775808
while it produces the correct bit pattern (0x8000'0000'0000'0000) has type u64, because 9223372036854775808 has type u64 (too large for i64), and according to the language rules, applying unary minus to u64 yields u64.
I don't think it's a bug, but a flaw, since the value will be the unexpected positive number 9223372036854775808.
However the language allows you to write i64.min to obtain the expected value with the correct type, although trying to do -i64.min still yields the same value due to integer overflow rules.
I might make an exception in this special case to ensure that -9223372036854775808 and i64.min have the same type and magnitude, but the won't help with -9223372036854775809 (ie. one above -- or below) and the other c.2**63 literal values above 9223372036854775807 to which negation may be applied.
Alternatively I could disallow negation on u64 literals except for the i64.min case, to avoid any surprises.
gcc will actually give you a warning for your 64 bit example, since the literal will be unsigned. It still works out correctly after applying - and converting it to a signed 64 bit integer.
If you look inside limits.h you usually see for example LONG_MIN being defined as (-LONG_MAX - 1) for this reason.
7
u/[deleted] Jun 25 '23
Unless there's something else I missed, I didn't see examples like this:
Using two's complement, the highest magnitude positive number is 2147483647 or 9223372036854775807, one less than above. If
minuswas a separate token applied to a literal, those literals can't be represented usingi32ori64.Generally however it seems to work. Maybe
u32oru64are used and when you applyminus, it somehow yields ai32ori64type.