Question

I'm checking if value ir between 0 and -0.2 like so:

float value = -0.1;
if (0 < value > -0.2f) { }

But I get error operator '>' cannot be applied to operands of type 'bool' and 'float'. I know, I could to that in other way using && operator in that if sentence, but I want to know, why does it gets detected as bool?

Was it helpful?

Solution

Take a look at this:

0 < value > -0.2f

Firstly 0 < value is evaluated, it returns bool value then it tries it compare bool to float number -0.2f, so it returns error, because it is not permitted.

You want to check if value is less and if value is greater than, so this is what you want to do:

if (0 < value && value > -0.2f) { }

OTHER TIPS

float value = -0.1;
if (0 < value > -0.2f) { }

Because you need to seperate the comparisons

Most langauges work left to right so

0 < value 

will be evaluated first. The result of this a boolean

Now your expression reads as

boolean > -0.2f

Which obviously will not work. You need

if (0 < value && value > -0.2f)

&& is a 'logical and' which combines the results of the logical computation to the left and right of it

It's because of the construction of your if statement. Try this instead:

if (0 < value && value > -0.2f) { }

What you've written is equivalent to this:

if ((0 < value) > -0.2f) { }

The 0 < value comparison is being evaluated, returning a boolean, which then becomes the operand for the second comparison. And, as the error message says, you can't use > to compare a boolean and a float.

Because of order of operations.

Basically, the compiler compile the if to something like this:

if ((0 < value) > -0.2f)

And the result of that is comparing a bool and an int, which is not good.

Try this instead:

if (0 < value && value > 0.2f)

Your if statement is syntactically incorrect. It requires a boolean expression between the braces.

http://msdn.microsoft.com/en-us/library/vstudio/5011f09h.aspx

if (0 < value > -0.2f) { }

Your statement is parsed like this:

if ((0 < value) > -0.2f) { }

(0 < value) evaluates to boolean expression. You're attempting to compare this to a float. Hence the error.

As you suggested yourself, the normal way to do this is to use &&.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top