0

It seems like the functions fun1 and fun2 should return the same values but the outputs are different. Can you explain why is it so?

#include <iostream>
using namespace std;
long long fun1(int, int, int );
long long fun2(int, int, int );
int main(){
    int l = 1039, b = 3749, h =8473;
   cout<<"Volume is equal to "<<fun1(l,b,h)<<endl;
   cout<<"Volume is equal to "<<fun2(l,b,h)<<endl;
}

long long fun1(int length, int breadth, int height){
    long long volume = length * breadth * height;
    return volume;
}
long long fun2(int length, int breadth, int height){
    return (long long)length * breadth * height;
}

output:

Volume is equal to -1355615565
Volume is equal to 33004122803
Tom
  • 303
  • 3
  • 14
  • You should add the language. It is pretty obvious it is C but without any tags people have very little chance to bump in your question. – Tom Jun 11 '20 at 08:48

1 Answers1

1

First case:

You are calculating everything in int type, and then casting to long long. Unfortunately the result is too big to fit in an int, so you have an overflow. Even if you cast it to a bigger type, that is too late, the overflow has already occured.

Second case:

You are casting to long long before actually doing the calculation. Thus, the calculation will be done using implicit conversion from int to long long and the result does fit in your container (which is long long now)… No overflow, life is beautiful!

Community
  • 1
  • 1
Tom
  • 303
  • 3
  • 14