Strange output without typing

I tried to execute this code through the gcc compiler:

#include <stdio.h>
int main()
{
    unsigned long long int x;
    x = 75000 * 75000;
    printf ("%llu\n", x);
    return 0;
}

But he gave the wrong conclusion.

Then I tried this:

#include <stdio.h>
int main()
{
    unsigned long long int x;
    x = (unsigned long long)75000 * (unsigned long long)75000;
    printf ("%llu\n", x);
    return 0;
}

And he gave the correct result!

Why is this so?

+5
source share
1 answer

An expression 75000 * 75000is a multiplication of two integer constants. The result of this expression is also an integer and may overflow. Then the result is assigned to unsigned long long, but it is already full, so the result is incorrect.

To write unsigned long long constants, use the suffix ULL.

x = 75000ULL * 75000ULL;

Now multiplication will not overflow.

+9
source

All Articles