-1

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?

Ariel Yael
  • 361
  • 2
  • 10

1 Answers1

2

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • why then [this](https://en.wikibooks.org/wiki/C_Programming/limits.h) site states that on 64-bit the size should be much larger? – Ariel Yael Aug 12 '21 at 12:01
  • 1
    @ArielYael It doesn't state such thing. It says: `LONG_MAX - ANSI standard maximum magnitude value - ≥+2,147,483,647` What is unclear about that? – eerorika Aug 12 '21 at 12:04
  • @ArielYael use the table here and look https://en.cppreference.com/w/cpp/language/types _"Win64 API - LLP64 or 4/4/8 (int and long are 32-bit, pointer is 64-bit)_" – Richard Critten Aug 12 '21 at 12:04
  • what do they mean by LONG_MAX -> 64 bit compiler ->+9,223,372,036,854,775,807 then? – Ariel Yael Aug 12 '21 at 12:05
  • @ArielYael Read the title of the column: "**typical** value". "Typical" doesn't mean "always" or "guaranteed" or "required". The author of that page evidently doesn't consider 64 bit Window's implementation typical. – eerorika Aug 12 '21 at 12:06
  • @eerorika Ok, in that case, I would like to know how to change it to be that – Ariel Yael Aug 12 '21 at 12:07
  • @ArielYael different platforms have different sizes - MS-Windows need to remain backward compatible with the 32-bit API so kept `long` as 32-bits. – Richard Critten Aug 12 '21 at 12:08
  • @ArielYael You cannot choose what size `long` is in your language implementation. You could choose to use a language implementation where `long` is 64 bit by not using windows. But it's generally better to not rely on `long` having a particular size allowing your program to be portable. – eerorika Aug 12 '21 at 12:08
  • @RichardCritten I understand, thank you – Ariel Yael Aug 12 '21 at 12:09
  • To avoid this type of problem in future, consider adding asserts to your code that confirm your assumptions about the size of your data types. – Tim Randall Aug 12 '21 at 13:52