Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit casting Integer calculation to float in C++

Is there any compiler that has a directive or a parameter to cast integer calculation to float implicitly. For example:

float f = (1/3)*5;
cout << f;

the "f" is "0", because calculation's constants(1, 3, 10) are integer. I want to convert integer calculation with a compiler directive or parameter. I mean, I won't use explicit casting or ".f" prefix like that:

float f = ((float)1/3)*5;

or

float f = (1.0f/3.0f)*5.0f;

Do you know any c/c++ compiler which has any parameter to do this process without explicit casting or ".f" thing?

like image 747
Ziddiri Avatar asked Jan 20 '26 10:01

Ziddiri


1 Answers

Any compiler that did what you want would no longer be a conforming C++ compiler. The semantics of integer division are well specified (at least for positive numbers), and you're proposing to change that.

It would also be dangerous since it would wind up applying to everything, and you might at some point have code that relies on standard integer arithmetic, which would silently be invalid. (After all, if you had tests that would catch that, you presumably would have tests that would catch the undesired integer arithmetic.)

So, the only advice I've got is to write unit tests, have code reviews, and try to avoid magic numbers (instead defining them as const float).

like image 94
David Thornley Avatar answered Jan 22 '26 03:01

David Thornley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!