Why does this code overflows even when casting?

100 Views Asked by At

I am studying for an exam that involves C. but I am encountering an error on the variables even when casting them. The code is copied from the powerpoint the professor gave us.

I was going through the Casting section that has this program written:

#include <stdio.h>

int main()
{
    long i;
    int j = 100000;

    i = (long)j * j;
    printf("%li", i);
}

I don't know why but that still gives me the output "1410065408" which of course means it's wrong. I even tried casting both variables:

    i = (long)j * (long)j;
    printf("%li", i);

I don't know how to move from now on, thanks in advance for the help

2

There are 2 best solutions below

3
Lundin On BEST ANSWER

The cast only saves the situation in case long happens to be 64 bit, which is often not the case.

In case it is 32 bit, then the maximum value of the signed long is 231-1 = 2.147 * 109.
But 100000 * 100000 = 10 * 109 so we get an integer overflow no matter the cast.

The solution is to use the portable int64_t from stdint.h instead:

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h> // for printing stdint.h types

int main()
{
    int64_t i;
    int j = 100000;

    i = (int64_t)j * j;
    printf("%" PRIi64, i);
}

(It's sufficient to only cast one operator of the +, since this means that the smaller operator of lower "conversion rank" gets implicitly promoted to the type of the larger one.)

0
Luis Colorado On

On a system wit 64bit long type, the system gives you the correct answer. In the system you use, the long type is 32bit and gives the answer you printed:

#include <stdio.h>

int main()
{
    int i;
    int j = 100000;

    i = (int)j * j;
    printf("%i", i);
}

after changing your long to int on my system (now calculations are done in 32bit) it gives the following answer:

$ a.out
1410065408$ _

(try to put a '\n' at the end of the line, and so you will not get the prompt immediately after the printed number, as in

    printf("%i\n", i);

You can ssolve your problem, ensuring that you will use a 64bit number:

#include <stdio.h>
#include <stdint.h>

int main()
{
    int64_t i;
    int j = 100000;
    i = (int64_t) j * j;
    printf("%lli", (long long) i);
}

Be careful because probably your machine lacks a int128_t type :)