Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple C question

Tags:

c

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?

like image 826
cbp Avatar asked Nov 22 '10 12:11

cbp


1 Answers

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);
}
like image 86
Svisstack Avatar answered Nov 01 '22 15:11

Svisstack