Does this do what I think it does?

Say I have the code,

1
2
3
4
5
6
7
8
	Class::Class(double value1, double value2, double value3) {
		if (value1 && value2 && value3) {
                        //do stuff
		}
		else {
                        //do stuff
		}
	}


Does this mean "if value1, value2 and value3 have been provided and been passed as arguments, do the following"

Or does it mean, "if value1, value2 and value3 are true, do the following"
It is impossible to get into this function without three input parameters having been provided.

Your second guess is the one. It means "if value one, evaluated as a boolean, is true, and the same for two and three, do the following"
Last edited on
Is there a big difference between that snippet and this one, though?

1
2
3
4
5
6
7
8
Class::Class(double value1, double value2, double value3) {
		if (0 != (value1 && value2 && value3)) {
                        //do stuff
		}
		else {
                        //do stuff
		}
	}


The reason I ask is because I get expected outputs when I run it either way, so Im just wondering when I should/can use the first snippet and when I shouldnt.
Last edited on
You're grossly mixing bools with numbers. It is well-defined, but it makes the code a lot less readable, and your intentions less clear.

0 != (value1 && value2 && value3)
This is comparing a integer (left hand side) to a boolean (right hand side), but the bool is implicitly cast to an int. I'll expand this out. In C++ boolean logic, 0 is the same thing as false, and a non-zero value is seen as true.

This is equivalent to:
false != (value1 != 0.0 && value2 != 0.0 && value3 != 0.0)

Which is equivalent to:
true == (value1 != 0.0 && value2 != 0.0 && value3 != 0.0)

Which is equivalent to:
(value1 != 0.0 && value2 != 0.0 && value3 != 0.0) (BTW, this is what I would prefer out of what has been given)

Which is equivalent to:
(value1 && value2 && value3)

_______________________________________

I personally would never equate a floating-point number to 0, because IEEE floating-point arithmetic is inherently inexact (unless dealing with sums of powers of 2... it's complicated). https://stackoverflow.com/questions/12124936/what-types-of-numbers-are-representable-in-binary-floating-point

I think there must some better way to set up your function/logic. Depends on what you're actually trying to accomplish with the checks.
Last edited on
Topic archived. No new replies allowed.