Is this a proper use of the logical "and" operator?
I'm looking at someone's code and they did:
if ( myNum > (num1 && num2 && num3) )
... with the intent of executing code when myNum is greater than num1, num2, and num3. Will this work?
edit: Thanks guys. I didn't think it would work, but I'm no expert, so I tho开发者_StackOverflowught I'd ask people who are.
Assuming the values are of a type like int
, in C or C++ this would first evaluate
(num1 && num2 && num3)
as
(num1 !=0) && (num2 != 0) && (num3 != 0)
The result would be either true
or false
in C++, and either 1 or 0 in C.
You would then compare myNum
to that result.
No - certainly not in C# or Java, at least. You want:
if ((myName > num1) && (myNum > num2) && (myNum > num3))
(It's possible that you don't need the brackets here - I can never remember operator precedence.)
It wouldn't work as written in Java or C# as &&
is an operator on Boolean operands, with a Boolean result. It's possible that it would compile/run in a less strongly-typed language, but I highly doubt that it will have the intended effect in any mainstream language.
No, that won't work. Why it won't work depends on the language, but (num1 && num2 && num3) will be evaluated first in all the languages you've tagged the question with. Provided (num1 && num2 && num3) actually compiles and evaluates to something, you will then get myNum > something.
Not in any language from the tags. Well, I think it might work in C and JavaScript, but certainly not as intended.
It might work in c++ if myNum, num1, num2 and num3 are a special type with operators > and && overloaded. But it will probably not worth it creating such a class which can handle this.
This is incorrect at least in C: http://codepad.org/R9IP0ZOr
int main()
{
int myNum = 10;
int num1,num2,num3 ;
num1 = 15;
num2 = 16;
num3 = 17;
if ( myNum > (num1 && num2 && num3) )
printf("%s","YES|GREATER");
else
printf("%s","NO|SMALLER");
} // prints "YES|GREATER" even though all numbers are greater than myNum
Correct statement should be :
if( (myName > num1) && (myNum > num2) && (myNum > num3) )
{
}
It is valid JavaScript code, but will probably work differently than expected by the person who wrote it.
It will actually end up evaluating if(myNum > num3)
since (num1 && num2 && num3)
will just return the value of num3
Or a bit more fancily:
if(Num > Math.Max(Num1,Math.Max(Num2,Num3)))
精彩评论