Search code examples
c++c64-bitoverflowlong-integer

windows uses long int as if in a 32-bit machine while in 64-bit


I'm using 10 64-bit. when running the following code for example, I get an overflow and a negative number is printed, while on a linux 64-machine I get the actual number printed:

#include <stdio.h>

int main() {
    long int a = 3845354610;
    printf("Hello, World!%ld\n", a);
    scanf("%ld", &a);
    return 0;
}

The output on windows is:

Hello, World!-449612686

and on linux it's the right output.

I tried using the --build-64bit flag in the CMake options in CLion. I'm using mingw-64 (D:\MinGW\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64).

I tried using the cmd to compile:

gcc -Wall -Wextra -Wvla -std=c99 main.c -o ma.exe

but the output was the same. How can this be fixed?


Solution

  • How can this be fixed?

    By using long long or std::int64_t. long is required / guaranteed to be at least 32 bits, and that's the size of long on (64 bit) windows.