Dipen Dadhaniya
Dipen Dadhaniya

Reputation: 4630

Type Casting In Arithmetic Expressions C++

    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 )

Upvotes: 0

Views: 1035

Answers (1)

Baum mit Augen
Baum mit Augen

Reputation: 50061

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).

Upvotes: 5

Related Questions