cbp
cbp

Reputation: 25638

Simple C question

I was born in the modern world, so I don't often need to deal with this sort of thing, but could someone explain how to get the correct number in the following code. Here is one attempt of many:

#define     X   2527
#define     Y   2463
#define     Z   3072

main()
{
long int c = X*Y*Z;
printf("%ld",c);
}

I'm just trying to print a long integer but it is always printing the wrong result. Am I getting integer overflows - if so how can I prevent them? Or is it my choice of printf formatter?

Upvotes: 5

Views: 324

Answers (4)

ramshankar
ramshankar

Reputation:

#define     X   2527.0
#define     Y   2463
#define     Z   3072

main()
{
double c = X*Y*Z;
printf("%lf",c);
}

you can also use double.

Upvotes: 0

Ofir
Ofir

Reputation: 8372

The problem is that the constants are not interpreted as long integers and the casting to long integer takes place only after the expression is calculated. You can cast them in the expression to solve this or simply define them as long constants. Also, long may not be enough, long long should be used instead if it is supported.

Upvotes: 3

Svisstack
Svisstack

Reputation: 16656

Overflow is ok, because you trying 34 bit number write to 32 bit variable (long int).

Use long long int and %lld in format string.

#define     X   2527LL
#define     Y   2463LL
#define     Z   3072LL

main()
{
long long int c = X*Y*Z;
printf("%lld",c);
}

Upvotes: 8

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22114

Yes, you are getting overflow. The answer will not fit into 32 bit signed integer, which long int is. You have to use 64 bit type, that is long long.

Also, you should do type casting, otherwise the intermediate calculation would overflow.

#define     X   2527
#define     Y   2463
#define     Z   3072

main()
{
long long c = (long long)X*Y*Z;
printf("%lld",c);
}

Upvotes: 1

Related Questions