Aneket
Aneket

Reputation: 33

Integer overflow and Multiplication of integers in c++

    int y ;
    y = 7000000000*1.0;

This does not give an error in cpp

Though

    int y ;
    y = 7000000000;

This leads to integer overflow

Can anyone please explain these two scenarios.

Upvotes: 3

Views: 197

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222323

In your C++ implementation, both y = 7000000000*1.0 and y = 7000000000 result overflowing what is representable in an int during conversion. For conversion from a floating-point type to an integer type, the behavior in the event of such overflow is not defined by the C++ standard. For conversion from one integer type to another, it is implementation-defined.

However, your compiler diagnoses the latter during compilation and fails to diagnose the former. This does not mean the former is okay (it is not), simply that the compiler does not report the problem (and is not required to by the C++ standard).

Upvotes: 6

Related Questions