0
    int a = 5 , b = 2 ;
    double ans1 = a / b ; // ans1 = 2
    cout << setprecision ( 4 ) << fixed << ans1 << endl ;

    unsigned short int c = USHRT_MAX , d = USHRT_MAX ;
    unsigned int ans2 = c + d ; // ans2 = 131070 
    cout << ans2 ;

What happens when the ( a / b ) is evaluated?

1) the result first stored in int ( variable type on the R.H.S ) and then converted into 64-bit double ( variable type on the L.H.S ) and then stored in the ans1 or first variables are converted into 64-bit double ( variable type on the L.H.S ) and then / takes place ?

2) if first evaluated as the variables type on R.H.S , then how the second one prints the correct ans ( because the ans is out of unsigned short int's limit )

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Dipen Dadhaniya
  • 4,550
  • 2
  • 16
  • 24

1 Answers1

5

In the first example, you first divide the two ints with truncating integer division and then assign the result of that (2) to ans1.

The second case is different in a subtle way: You chose integer types that are smaller than int. Thus, before any arithmetic operator acts on them, they both get converted to int (if that fits, as it does here, to unsigned int otherwise) while preserving their values, and on int the operation you showed does not overflow. Then you assign the result (which has type int) to the unsigned int, and since it is non-negative, nothing strange happens.

If you tried the second example with unsigned int instead of unsigned short, you could observe the "integer overflow" (which is no real overflow because unsigned arithmetic wraps).

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
  • As in second case unsigned short int are smaller than int hence they both get converted to int , then in the first case also int is smaller than double , so why not same rule of casting ? Or it is just for ( / ) operator ( special case ) ? . – Dipen Dadhaniya Jul 22 '15 at 07:42
  • #include using namespace std ; int main() { int a = 1000000 , b = 1000000 ; long long int ans = a * b ; cout << ans << " " << a << " " << b << endl ; long long int c = 1000000 , d = 1000000 ; long long int ans2 = c * d ; cout << ans2 << " " << c << " " << d ; return 0; } // then what about this ? int is smaller then long long int , but first cout prints wrong , but second one correct – Dipen Dadhaniya Jul 22 '15 at 07:53
  • 1
    @knock_out This is controlled by a kind of complex set of rules, the so called "usual arithmetic conversions". They are for example explained [here](https://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Core-C-/Stephan-T-Lavavej-Core-C-7-of-n), starting around 19:20 if you don't care about the rest of the talk, or [here](http://stackoverflow.com/a/28142965/3002139) if you only need the wording without explanation. – Baum mit Augen Jul 22 '15 at 09:40