C2296: '|': illegal, left operand has type 'float'

Viewed 447

I am trying to compare, in a clean and FAST way (by logic) if three variables are 0, they are all floating point numbers, IEEE 754.

float x;
float y;
float z;

if(((x | y | z) == 0.0f)) { ... }

But, I keep getting:

main.cpp(15): error C2296: '|': illegal, left operand has type 'float'
main.cpp(15): error C2297: '|': illegal, right operand has type 'float'
main.cpp(18): error C2296: '|': illegal, left operand has type 'float'
main.cpp(18): error C2297: '|': illegal, right operand has type 'float'

I read something about,

std::numeric_limits<T>::is_iec559
std::numeric_limits<float>::epsilon()
std::fabs()

and Epsilon 10^−7

2 Answers

The bitwise operators are only defined for integral types. A float is not an integral type.

Don't micro-optimise like this. Write your intention clearly, and leave the optimisation strategy to the compiler.

You cannot perform a "bitwise OR" on floating point numbers.

If you really wanted to, you could directly inspect the bits representing the floating point numbers and perform integer comparisons on them, which is the sort of thing you might do on an embedded system with no FPU and no floating point library.

structure of float and double

See https://bob.cs.sonoma.edu/IntroCompOrg-RPi/sec-ieee.html and https://en.wikipedia.org/wiki/IEEE_754-1985 for more.

Whilst that can be a fun endeavour, you're almost always better off making your code readable so that it can be maintained; leaving optimisation to the compiler.

In addition, I would personally almost never compare a floating point with zero, but check that its abs is less than a very small number.

Related