Log in

View Full Version : and, or - 'single' characters?



magicyte
11-19-2008, 02:35 AM
In some programs, I have seen code in which the programmer does this:


if (i&1) {
do_somthing();
}

Why is there only one ampersand and not two? If anyone could please explain how the 'single' character of operators work, including '|' and '&' or any others not listed please?

-magicyte

Medyman
11-19-2008, 02:45 AM
Perhaps it would help if you told us where you've seen such syntax. As far as I'm aware, that's not a valid logical conditional.

magicyte
11-19-2008, 02:59 AM
I've seen it in C++ tutorial books. Sorry- I really shouldn't have posted this here, huh. :o

^ I've also seen this done in C++ code and bits of JavaScript. ^

Here is one link:

http://www.cprogramming.com/tutorial/bitwise_operators.html <- Don't understand this

if you understand what I mean, is it possible in JavaScript or PHP (client-side / server-side)?

Again, I shouldn't have posted this thread here. Mod/admin, please move/relocate thread... Thank you!

-magicyte

hmsnacker123
12-11-2008, 12:31 AM
Ive seen this in php! and i was puzzled as to what it was. (One ampersand).

Twey
12-11-2008, 03:44 PM
Those are not logical operators (http://javascript.wikia.com/wiki/Boolean#Combination_operators) but bitwise operators (http://javascript.wikia.com/wiki/Number#Bitwise_Operators). In weakly-typed languages where 1 is coerced to true and 0 to false they are mostly equivalent, but lack short-circuit behaviour. As such, they will perform worse in some situations and should not be used where a logical operator is intended.

In languages where the logical operators yield the terminating value, they will also result in a different return value in most cases:
// Javascript
true && false // false
true & false // 0
({}) || undefined // ({}) (only the first operand matters because the result would be the same no matter the second; the object is the terminating value, and is returned)
({}) | undefined // 0 (the object is coerced to 1, and undefined to 0)

function foo() {
return true;
}

function bar() {
return false;
}

bar() && foo() // false; only bar is called
bar() & foo() // 0; both bar and foo are called

In strongly-typed languages, using a bitwise operator on boolean values will yield an error:
-- Haskell
import Data.Bits

1 .&. 2 :: Int -- 0

True .&. False :: Int
-- Couldn't match expected type `Int' against inferred type `Bool'
-- In the expression: True .&. False :: Int