Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weird output without typecasting

Tags:

c

casting

I was trying to execute this code through gcc compiler:

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

But it gave wrong output.

I then 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 it gave correct output !

Why is this so?

like image 346
Snehasish Avatar asked Jun 17 '12 08:06

Snehasish


1 Answers

The expression 75000 * 75000 is the multiplication of two integer constants. The result of this expression is also an integer and can overflow. The result is then assigned to an unsigned long long, but it has already overflowed so the result is wrong.

To write unsigned long long constants use the ULL suffix.

x = 75000ULL * 75000ULL;

Now the multiplication will not overflow.

like image 108
Mark Byers Avatar answered Oct 15 '22 14:10

Mark Byers