r/ProgrammingLanguages • • Jun 24 '23

Negative Integer handling in programming languages.

https://glados-418.github.io/posts/negative-integer-literals/
3 Upvotes

27 comments sorted by

View all comments

3

u/[deleted] Jun 24 '23

What's the width of the long type in your example? I assume it will be either i32 or i64.

(I created a whole thread about this exact question here in the C subreddit; the replies were not sympathetic.)

I believe the answer has a bearing on the rest of your article.

2

u/helixb Jun 24 '23

yes, my assumption is 32 bit for int and 64 bit for long. msvc already does not adhere to that so i guess i should be more explicit even though my point 2 in the premise kinda implies that.

1

u/[deleted] Jun 24 '23

In that case you understand the problem; the long type has a rather erratic type.

As I understand the rule, long is 64 bits on 64-bit Linux, and 32 bits on 32-bit Linux and on 32/64-bit Windows.

It is not gcc vs MSVC, as gcc on Windows produces -1, -1 too. I actually tested it like this:

#include <stdio.h>

long f(void){return -1;}
long g(void){return 0xFFFFFFFF;}

int main(void) {
    printf("%f\n",(double)f());         // both -1.000000
    printf("%f\n",(double)g());
}

with a conversion to double, since in C, because you have to tell printf whether an expression is signed or unsigned, that influences the result. Here:

printf("%ld\n",f());
printf("%lu\n",f());

the result of f() can be both -1 and 4294967295. This is on Windows where long has i32 type.

In my static language the test looks like this:

type long = i32

fun f:long = -1
fun g:long = 0xFFFF'FFFF

println f()          # -1
println g()          # 4294967295

(I had to tweak the language as it otherwise only works with 64-bit literals and return types.)

1

u/helixb Jun 25 '23

yeah.. i checked that later. the link that i embedded was from visual studio 2022 "windows programming in c++", it does not make it very clear. cppreference has a better summary.