Consider the following code:
#include <stdio.h>
int main()
{
printf("%d", 300 * 300 / 300);
return 0;
}
This code when run on a standard GCC compiler gives the result as 300 but when i run it using Turbo C, the result is 81. Why is it so?
I understand that TC uses 2 bytes for storing integers, and the result 300 * 300 would clearly exceed this limit, but before it is printed it is again divided with a 300 right?
And additionally what is computed first? 300 / 300 or 300 * 300?)
What is the reason for this behavior??
Before it prints it divides it by 300, but the overflow already happend, since integer literals are evaluated as
ints, when you divide, you already with the overflowed int result.Since
*and/has the same priority, the*is evaluated first (since evaluation is left to right)You can, however, do either
300 * (300/300)or300L * 300 / 300